game
dsde
dsdd
dsdsw
ds
ds
ds
ds
ds
ds
为什么addclass之后,active没有绑定click事件。
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
题主,想象下这个过程。
js代码在载入后,只会自动运行一次。所以是不会一直监视着题主的DOM的!
这样在代码运行时,只会将你的事件,绑定在那个瞬间,在DOM树中类名为active的DOM元素上(不要被JQuery的选择器表达式迷惑了,事件绑定最终还是要回到DOM元素上)。
所以楼主的写法只是将事件绑定在事件绑定时唯一有active类名的那个DOM元素上了!这就是其他元素没有反应的原因。
正确的绑定方法就是事件委托 @TomDong 已经给出解释,@StephenLee 也给出代码咯。
建议楼主有时间的话多了解一下javascript的实现机制:)
$('table').on('click','.active',function(){})
.on( events [, selector ] [, data ], handler(eventObject) )
events
Type: String
One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin".
selector
Type: String
A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.
官方文档里有说,当selector为null的时候,其将一直指向$(".active"),由于你一开始$(".active")就是最中间的那个元素,所以它一直都不会变,其相当于click事件
关于“将侦听事件绑在要监听的元素的父级元素上”,举一个例子:
$("#comment-form").on("click", ".addNew", addComment),和$("body").on("click", "#comment-form .addNew", addComment)这两种写法都可以完成同样的功能。但是“定义”on函数本身前者要比后者费时(因为查找#comment-form要比查找body费时),所以说,如果想节省首次进入页面的js的加载时间就用后者,但那样的话每次发生click事件,查找的耗时就会多,如何权衡就要看实际业务了。