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

本文介绍了jQuery中live()方法被废弃后,如何使用on()、delegate()等替代方案来实现事件委托,确保为动态生成的元素绑定事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最开始用惯了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()方法的

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

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值