body click的绑定与元素click的绑定

1、通常使用jQuery绑定click如下:

$('div.class').on('click',function(){
    ......
})

此种方式无法绑定动态新增的元素,如:

$('div.demo').on('click',function(){
    $(this).removeClass('demo'); //A
    $(this).siblings().addClass('demo');
})

元素A移除class.demo,他的兄弟节点添加class.demo,按理他的兄弟节点添加class后也绑定了click事件,可并非如此

解决方案:

$('body').on('click','div.demo',function(){
    $(this).removeClass('demo');
    $(this).siblings().addClass('demo');
})

绑定body,然后传入元素参数,可绑定动态添加的元素。

另外在重新初始化数据后(如搜索查找更新),为防止click多次触发,先接触绑定

$('body').off('click');
$('body').off('keypress');
...
原文地址:https://www.cnblogs.com/moon-future/p/5955710.html