首页 > 网站 > WEB开发 > 正文

jQuery使用on()绑定动态生成元素的事件无效

2024-04-27 14:11:37
字体:
来源:转载
供稿:网友

jQuery使用on()绑定动态生成元素的事件无效

jquery on()方法是jquery1.7+后才使用的

由于需求:动态添加了以下代码

<tr class="pj" data-val="no"><th id="first_tr" rowspan="1" colspan="1" data-id="xxx">自我评价<button type="button" title="添加" id="add_rw"/> </th><td colspan="2"><input type="text" name="task_name" datatype="title" Caption="自我评价" MAXLEN="100" ISNULL="notnull"/></td> <td colspan="1"><input type="checkbox" name="result" value="2"/></td> <td colspan="1"><input type="checkbox" name="result" value="1"/></td> <td colspan="1"><input type="checkbox" name="result" value="0"/></td> </tr>

  绑定是这么写的

       $("input[name='result']").on("click",function(){            var len =     $(this).parent().siblings().children("input").attr("checked",false);            $(this).attr("checked",true);            });

发现对于动态添加的没有起到监听作用,那么对代码进行修改,把监听对象改成静态的就可以了

       $("table").on("click","input[name='result']",function(){            var len = $(this).parent().siblings().children("input").attr("checked",false);            $(this).attr("checked",true);            });

这里table是非动态添加的父节点,由于.pj也是动态生成的,写.pj 作为父节点是没有效果的


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表