第一種監聽方式,也是最普遍使用的方式,是直接在代碼上載入事件,產生效果:
<table>
<tr onmouseover='this.style.backgroundColor="red"' onmouseout='this.style.backgroundColor=""'><td>text1</td><td>text2</td></tr>
<tr onmouseover='this.style.backgroundColor="red"' onmouseout='this.style.backgroundColor=""'><td>text3</td><td>text4</td></tr>
<tr onmouseover='this.style.backgroundColor="red"' onmouseout='this.style.backgroundColor=""'><td>text5</td><td>text5</td></tr>
</table>
第二種監聽方式,是使用DOM的方式擷取對象,並載入事件:
<table>
<tr><td>text1</td><td>text2</td></tr>
<tr><td>text3</td><td>text4</td></tr>
<tr><td>text5</td><td>text5</td></tr>
</table>
<script>
doms = document.getElementsByTagName('tr');
for(i=0;i<doms.length;i++)
{
doms[i].onmouseover = function()
{
this.style.backgroundColor = "red";
}
doms[i].onmouseout = function()
{
this.style.backgroundColor = "";
}
}
</script>
第三種監聽方式,是使用標準的addEventListener方式和IE私人的attachEvent方式,因為IE的attachEvent方式在參數傳遞時的缺陷,這個問題被搞得稍許有些複雜了:
<table>
<tr><td>text1</td><td>text2</td></tr>
<tr><td>text3</td><td>text4</td></tr>
<tr><td>text5</td><td>text5</td></tr>
</table>
<script>
doms = document.getElementsByTagName('tr');
function show_color(where)
{
this.tagName ? where = this : null
where.style.backgroundColor = "red";
}
function hide_color(where)
{
this.tagName ? where = this : null
where.style.backgroundColor = "";
}
function for_ie(where,how)
{
return function()
{
how(where);
}
}
for(i=0;i<doms.length;i++)
{
try
{
doms[i].addEventListener('mouseover',show_color,false);
doms[i].addEventListener('mouseout',hide_color,false);
}
catch(e)
{
doms[i].attachEvent('onmouseover',for_ie(doms[i],show_color));
doms[i].attachEvent('onmouseout',for_ie(doms[i],hide_color));
}
}
</script>
在綁定多個相同的事件的時候,前兩種方法會產生覆蓋,而第三中方法則會同時執行多個事件。