Blogger Information
Blog 5
fans 2
comment 1
visits 4635
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
jQuery中事件添加与删除on()与off()
zhihuanwang的博客
Original
715 people have browsed it

    为了让网页更加生动有趣,动态的展现给用户。添加事件必不可少,今天我来写下jQuery关于这方面的内容,举个简单的案例:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <script src="js/jquery-3.2.1.min.js"></script>    <title>jQuery中事件添加与删除on()与off()</title>    <script> $(document).ready(function () { $("<div></div>").appendTo('body').css('width','200').css('background-color','red').css('height','200').on('click',function () { $(this).css('background-color','skyblue')            }).on('mouseleave',function () { $(this).html('jQuery是一个很好的JS库')            })//            $('div').off('mouseleave') })    </script></head><body></body></html>

添加事件其实还可以:

$('input').click(function () {    //处理代码});//或者是$('.clickme').bind('click', function() {    // Bound handler called.});



这两个方法对已经加载好的元素定义事件,那些后来添加插入的元素则需要另行绑定事件。

用live可以解决这个问题:

$('.clickme').live('click', function() {   // Live handler called.});


即使是在后面动态插入的元素,也会被绑定事件,

$('body').append('<div class="clickme">Another target</div>');

问题:使用jQuery的live()方法绑定事件,有时会出现重复绑定的情况,如,当点击一个按钮时,此按钮所绑定的事件会并执行n遍。

解决:使用die()方法,在live()方法绑定前,将此元素上的前面被绑定的事件统统解除,然后再通过live()方法绑定新的事件。比如:

//先通过die()方法解除,再通过live()绑定$("#selectAll").die().live("click",function(){    //事件运行代码});//先通过die()方法解除,再通过live()绑定$("#selectAll").die().live("click",function(){    //事件运行代码});


然而尴尬的是jQuery 1.7以后就不支持了As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live(). - .live() | jQuery API Documentation

差不多意思是:

从jQuery 1.7开始,.live()方法已被弃用。使用.on()添加事件处理。老版本的jQuery用户应该优先使用.delegate().live()。

多么波折的发展。。。




Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!