javascript當(dāng)中綁定事件和方法
綁定事件和方法
馬克- to-win:馬克 java社區(qū):防盜版實名手機尾號: 73203。
馬克-to-win:once, long time to know that "script" must be put in behind, while "input" must be put in front,
otherwise document.getElementById("button1"); can not find the "button1",alert("button1 is "+ button1); 結(jié)果就是null,為什么這次跟往常我們的印象不一樣了呢?因為往常我們先寫一段script,之后在body中寫上諸如<INPUT TYPE="button" onclick="abc",之類的話,這樣上面的abc這樣的代碼開始不會被執(zhí)行,里面的諸如document.getElementById ("button1");也就正確了。這里為什么跟往常不一樣呢?因為要在一開始時,先給button綁上事件代碼,否則button無事件響應(yīng)。
例 8.1(commonEventPrerequisiteIEFF.html)
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
</head>
<INPUT TYPE="button" NAME="button1" ID="button1" VALUE="單擊我"/>
<script>
function testie()
{
alert("單擊按鈕ie");
}
function testFF()
{
alert("單擊按鈕FireFox");
}
/**/
/*obj.addEventListener("click",function(){func("看到我了吧");},false);
the third argument is: A Boolean flag value that indicates whether the event listener should
use bubbling (由里向外) or capture (由外向里) event propagation. 只要我們
知道第三個參數(shù)和事件冒泡有關(guān)就可以了。缺省值為假,即冒泡的意思。具體例子參考后面的事件冒泡例子。
*/
var button1 = window.document.getElementById("button1");
alert("button1 is "+ button1);
alert("document.all is" + document.all);
alert(typeof(window.addEventListener) + " is typeof window.addEventListener");
alert(typeof(window.attachEvent) + " is typeof window.attachEvent");
alert(window.addEventListener + " is window.addEventListener");
alert(window.attachEvent + " is window.attachEvent");
if (typeof window.attachEvent === "object")
{
alert("ie");
button1.attachEvent("onclick", testie);
}
if (typeof window.addEventListener === "function")
{
alert("firefox");
button1.addEventListener("click", testFF, false);
}
// button1.addEventListener("click",test,false);
//button1.attachEvent("onclick" , test);
var str = "";
</script>
例 8.2(commonEventPrerequisite1IEFF.html)
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
</head>
<INPUT TYPE="button" NAME="button1" ID="button1" VALUE="單擊我"/>
<script>
function testie()
{
alert("單擊按鈕ie");
}
function testFF()
{
alert("單擊按鈕FireFox");
}
/*obj.addEventListener("click",function(){func("看到我了吧");},false);
the third argument is: A Boolean flag value that indicates whether the event listener should
use bubbling (bottom up) or capture (top down) event propagation. Both types
can be registered separately but must also be removed separately. 只要我們
知道第三個參數(shù)和事件冒泡有關(guān)就可以了。
*/
var button1 = window.document.getElementById("button1");
if (typeof window.attachEvent === "object")
{
alert("ie");
button1.onclick = testie;
}
if (typeof window.addEventListener === "function")
{
alert("firefox");
button1.onclick = testFF;//這種方法無法設(shè)置冒泡或capture。
}
// button1.addEventListener("click",test,false);
//button1.attachEvent("onclick" , test);
var str = "";
</script>