JavaScript中对事件的三种监听方式


第一种监听方式,也是最普遍使用的方式,是直接在代码上加载事件,产生效果:
<table>
<tr οnmοuseοver='this.style.backgroundColor="red"' οnmοuseοut='this.style.backgroundColor=""'><td>text1</td><td>text2</td></tr>
<tr οnmοuseοver='this.style.backgroundColor="red"' οnmοuseοut='this.style.backgroundColor=""'><td>text3</td><td>text4</td></tr>
<tr οnmοuseοver='this.style.backgroundColor="red"' οnmοuseοut='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>

在绑定多个相同的事件的时候,前两种方法会产生覆盖,而第三中方法则会同时执行多个事件。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值