您的位置:首页 > Web前端 > JavaScript

js 事件绑定on()的用法,以及对于其他绑定事件的比较

2017-05-12 09:25 567 查看
事件绑定

1,jQuery 中的on绑定事件的方法:

on() 方法在被选元素及子元素上添加一个或多个事件处理程序。

自从jQuery 1.7 版本之后,on() 方法是bind() 、live()、和 delegate() 方法的新的替 代品,所以我推荐使用这个方法,他简化了jQuery 代码库。

例子1:

<button class="btn">on点击我</button>
<script>
$().ready(function(){
$('.btn').on('click',function(){
$(this).css('background','green');
})
})
</script>


跟on()方法类似的 几种事件绑定函数(bind() 、live()、和 delegate() )的用法以及,怎么用on()方法来替代这些方法达到同样的效果:

① : 利用on()方法代替bind()方法达到同样的效果

<button class="btn">on点击我</button>
<button class="btn1">bind点击我</button>
<script>

$().ready(function(){
$('.btn').on('click',function(){
$(this).css('background','green');
})
})
$().ready(function(){
$('.btn1').bind('click',function(){
$(this).css('background','#yellow');
})
})

</script>


② : 利用on()方法代替live()方法达到同样的效果

<button class="btn">on点击我</button>
<button class="btn1">live点击我</button>
<script>
$().ready(function(){
$('.btn').on('click',function(){
$(this).css('background','green');
})
})
$().ready(function(){
$('.btn1').live('click',function(){
$(this).css('background','yellow');
})
})
</script>


③ : 利用delegate()方法代替live()方法达到同样的效果

<div id="div1">
<p>on方法点击.</p>
</div>

<div id="div2">
<p>delegate方法点击.</p>
</div>

<script>
$().ready(function(){
$('#div1').on('click','p',function(){
$(this).css('background','green');
})
})
$().ready(function(){
$('#div2').delegate('p','click',function(){
$(this).css('background','yellow');
})
})
</script>


2,jQuery 中的on绑定事件解除的方法: off()

提示:如果需要移除绑定的事件,不让它执行,那么需要是要 off() 方法

<button class="btn">on点击我</button>
<button class="btn2">点击我取消绑定的点击事件</butto
4000
n>
<script>
$().ready(function(){
$('.btn').on('click',function(){
$(this).css('background','green');
});
$('.btn2').click(function(){
$('.btn').off('click')
})
})
</script>


3,jQuery 中的on方法添加多个事件处理程序

注释:做了一个鼠标移入移出自动添加class的效果

<div id="div2">
<p>Click to set background color using the delegate() method.</p>
</div>
<style>
.red1{color:#c90b45;}
</style>
<script>

$().ready(function(){
$('#div2 p').on('mouseover mouseout',function(){
$(this).toggleClass('red1')
});

})


多个事件绑定还有另外一种写法,我感觉这种方法更加方便,更容易修改:

注释:做了一个鼠标移入移出,以及点击自动改变文字颜色的效果

<div id="div2">
<p>Click to set background color using the delegate() method.</p>
</div>
<style>
.red1{color:#c90b45;}
</style>
<script>
$().ready(function(){
$('#div2 p').on({
mouseover: function(){
$(this).css('color','#c90b45');
},
mouseout: function(){
$(this).css('color','green');
},
click: function(){
$(this).css('color','#000');
}
});

})
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jquery delegate on
相关文章推荐