[转载]JQ中将事件绑定在动态添加的标签上(live/on/bind/delegate)

[转载]http://blog.csdn.net/me_phper/article/details/51452973

最开始用惯了live()方法、但后面JQ版本将之移除了(原因:方法本身就存在一些问题);

可用如下几种代替使用: 
1、on()方法示例

/*事件委派-给新增的option也能触发onchange事件*/
    $('#batchid_list').on('change', function () {
        var batchid = $("#batchid_list").find("option:selected").val();
        if (myDatatable == null) {
            showdatatable(batchid);
        } else {
            myDatatable.column(0).search(batchid);
            myDatatable.draw(true);
        }
    });

 

 

2、上面方法失效时仍用on()方法(有时候on方法也存在失效的情况)则可以尝试下面on另外一种用法:

 $(document).on("click", "#to_dispatch", function() {
       var batchid = $("#batchid_list").find("option:selected").val();
        if (myDatatable == null) {
            showdatatable(batchid);
        } else {
            myDatatable.column(0).search(batchid);
            myDatatable.draw(true);
        }
    });

 

 

3、如果可用delegate()方法,也可以使用,那也是可以使用delegate()方法的

1    $('#batchid_list').delegate('change', function () {
2        var batchid = $("#batchid_list").find("option:selected").val();
3         if (myDatatable == null) {
4             showdatatable(batchid);
5         } else {
6             myDatatable.column(0).search(batchid);
7             myDatatable.draw(true);
8         }
9     });

 

 

4、用.bind()的代价是非常大的,它会把相同的一个事件处理程序hook到所有匹配的DOM元素上

参考文章: 
jQuery 中bind(),live(),delegate(),on() 区别: 
http://blog.csdn.net/panfang/article/details/21705681

posted @ 2016-11-09 15:42  张志健  阅读(214)  评论(0)    收藏  举报