jQuery 问题收集
1、页面动态生成的dom元素,监听事件失效。需用事件代理进行监听。
对于动态绑定元素可以这样写
$(document).on('click', '.xxx', function() {
// do something
});
$(document)可以改成要绑定事件元素的父节点
.xxx 就是指的当前元素
这样就可以实现事件的代理
.on(events, callback)
只能绑定页面已有元素的事件。.on(events, selector, callback)
则是在 已有的元素 上绑定 代理的 事件处理器 (addEventListener
实际上在该已有元素上调用),但只有事件的实际 source
是其子代元素并且符合 selector
时, callback
才会以该实际 source
为 this
指向的对象被调用。
For example:
$(document).on("click", "a", function () {
console.log(this.tagName.toLowerCase()); // "a"
return false;
});
这样即可监听页面创建时尚未存在的 <a>
元素所产生的事件。
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.
In addition to their ability to handle events on descendant elements not yet created, another advantage of delegated events is their potential for much lower overhead when many elements must be monitored.
渣翻译:
委托事件 的优势是可以处理在其后添加入文档的子代元素所产生的事件。通过选择一个添加委托事件时必然存在的元素,你可以使用委托事件以避免频繁添加和移除事件处理器的需求。例如,该元素可以是在 MVC 设计中视图的包含元素,或者如果事件处理器要监控文档中所有冒泡的事件时,则是
document
.document
在载入任何其它 HTML 之前即可在文档的头部获得,所以在此添加事件处理器而不用等待document
的ready
是安全的。
除了处理尚未创建的子代元素上产生的事件,委托事件的另一个优势是需要监控多个元素时的性能更好。