問題描述
我正在努力弄清楚為什么 mouseover 事件不能與 .on 處理程序一起使用,該處理程序是從 ajax 動態創建的元素.似乎唯一可行的是帶有 .live 的代碼,但我知道它已被棄用.
$(".dropdown ul li").live("mouseover", function() {alert('鼠標懸停工作');});
但是,當我嘗試使用 .on 時,它不起作用 - 無論我嘗試什么變體(document.ready、.mouseover 等)
$(".dropdown ul li").on("mouseover", function() {alert('鼠標懸停工作');});
事件處理程序位于代碼的底部,因此它們最后執行.有人知道我做錯了什么嗎?
將 .on
用于具有動態事件委托 http://api.jquery.com/on/ - 你的主選擇器是一個存在的static parent:
$(".static-parent").on("event1 event2", ".dynamic-child", function() {
或者在你的情況下:
$(".dropdown").on("mouseover", "li", function() {alert('鼠標懸停工作!!!!!!!!!');});
<塊引用>
委托事件的優點是它們可以處理來自以后添加到文檔的后代元素的事件.通過選擇在附加委托事件處理程序時保證存在的元素,您可以使用委托事件來避免頻繁附加和刪除事件處理程序的需要.例如,該元素可以是模型-視圖-控制器設計中視圖的容器元素,或者如果事件處理程序想要監視文檔中的所有冒泡事件,則可以是文檔.在加載任何其他 HTML 之前,文檔元素在文檔的頭部是可用的,因此在此處附加事件是安全的,而無需等待文檔準備好.
還要確保使用 DOM 就緒 函數
jQuery(function($) {//DOM 現已準備就緒,$ 別名已保護$(".dropdown").on("mouseover", "li", function() {alert('鼠標懸停工作!!!!!!!!!');});});
I'm pulling my hair out trying to figure out why the mouseover event won't work with the .on handler with a dynamically created element from ajax. The only thing that seems to work is the code with .live but I understand that it is deprecated.
$(".dropdown ul li").live("mouseover", function() {
alert('mouseover works');
});
However, when I try using .on, it will not work - no matter what variations I try (document.ready, .mouseover, etc etc)
$(".dropdown ul li").on("mouseover", function() {
alert('mouseover works');
});
The event handlers are at the bottom of the code, so they are executed last. Anyone have an idea of what I'm doing wrong??
Using .on
for newly generated elements with dynamic event delegation http://api.jquery.com/on/ - where your main selector is an existent static parent:
$(".static-parent").on("event1 event2", ".dynamic-child", function() {
or in your case:
$(".dropdown").on("mouseover", "li", function() {
alert('mouseover works!!!!!!!!!');
});
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.
Also make sure to use a DOM ready function
jQuery(function($) { // DOM is now ready and $ alias secured
$(".dropdown").on("mouseover", "li", function() {
alert('mouseover works!!!!!!!!!');
});
});
這篇關于事件不適用于動態創建的元素的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!