jquery中$(selector).on(events [, selector] [,function()])为动态添加的内容绑定事件注意事项

jquery中$(selector).on(events [, selector] [,function()])为动态添加的内容绑定事件注意事项

如果前端用jquery进行开发 则对动态添加的元素进行事件绑定是一种经常碰到的情况,而在使用过程中经常会遇到.on()绑定事件失效的问题

问题分析

在开发过程中遇到一个高级检索的开发问题,需要动态增减筛选条件,效果如下:
jquery中$(selector).on(events [, selector] [,function()])为动态添加的内容绑定事件注意事项
需要具有动态增减的效果
jquery中$(selector).on(events [, selector] [,function()])为动态添加的内容绑定事件注意事项
html dom树结构如下:
jquery中$(selector).on(events [, selector] [,function()])为动态添加的内容绑定事件注意事项
需要生成重复的

…</> html代码添加到form中,最错误的做法就是直接在新生成的html 元素中添加事件

错误一

<span class="glyphicon glyphicon-trash delete-icon" onclick="deleteItem()"></span>

<span class="glyphicon glyphicon-plus add-icon" onclick="addItem()"></span>

这种是最容易出错的,对于动态生成的html元素直接进行添加事件是没有作用的 应该通过$(selector).on(events [, selector] [,function()]) 方式来绑定事件

错误二

$(".deleteSearch span").on("click",function() {
            //if the last one  add the addtion button
            var index = $(this).parents(".modal-body .form-group").index();
            if ($(".modal-body form .form-group:last").index() == index) {
                index = index -1;
                $(".modal-body form .form-group .addition")[index].style.display = 'block';
            }
            //$(this).parents(".modal-body .form-group").css("display","none");
            $(this).parents(".modal-body .form-group").remove();
        });

用这种方式进行的时间绑定对于dom树中已经存在的元素的事件绑定是有用的,但是对于新增的元素绑定的事件不起作用
这是因为你绑定事件的时候还没有不存在(&quot;.deleteSearchspan&quot;)dom,(&quot;.deleteSearch span&quot;)的dom,所以你要通过父节点去查找这个(".deleteSearch span")的子节点
正确写法如下:

$(".modal-body form").on("click",'.deleteSearch span',function() {
            //if the last one  add the addtion button
            var index = $(this).parents(".modal-body .form-group").index();
            if ($(".modal-body form .form-group:last").index() == index) {
                index = index -1;
                $(".modal-body form .form-group .addition")[index].style.display = 'block';
            }
            //$(this).parents(".modal-body .form-group").css("display","none");
            $(this).parents(".modal-body .form-group").remove();
        });

通过其在dom书中已经存在的父节点进行查找元素绑定!!!