2014-01-10 32 views
0

我管理的鼠標懸停和鼠標移開的DOM元素,我怎樣才能到鼠標,鼠標中添加事件進行動態DOM元素

$(".selector").hover(function(){ 
    console.log('in'); 
},function(){ 
    console.log('out'); 
}); 

但它並不適用於動態內容的工作,哪有我爲動態元素做同樣的事情。

+0

動態元素意味着你通過ajax或類似的東西?的 –

+0

可能重複的[事件綁定上動態創建的元素?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) –

+0

沒有正在使用的插件,它創建從JSON對象元素,在隱藏字段 –

回答

5

可以使用.on()方法。 n注意hovermouseentermouseleave事件,而不是mouseovermouseout事件的簡寫。

另外,性能的角度來看,這將是更好的選擇關閉靜態父元素,而不是document對象。

$(document).on({ 
    mouseenter: function() { 
     console.log('in'); 
    }, 
    mouseleave: function() { 
     console.log('out'); 
    } 
}, '.selector'); 
+0

我從來不知道該語法存在 –

+0

@KevinBowersox它在DOC中,第二個sig:'events 類型:PlainObject'但在DOC中缺少示例:( –

+0

@ A.Wolff其實有一個例子,搜索對於'同時安裝使用純object.'惡劣多個事件處理程序,我們不能超到它 –

1
$(document).on("mouseleave", ".selector", function(){ 
    //code here 
}); 

$(document).on("mouseenter", ".selector", function(){ 
    //code here 
}); 

on功能將附加的事件處理程序,用於偵聽所選對象所指定的事件(第一個參數)。當事件被觸發並冒泡到選定元素(在我們的例子中是文檔)時,它會檢查目標元素是否與第二個參數(選擇器)相匹配。如果目標匹配提供的功能被觸發。在我的示例中,我選擇document,但是您應該選擇最接近的非動態父級,以獲得更好的性能。

-2
$(".selector").mouseover(function(){ 
    console.log('in'); 
}); 

$(".selector").mouseleave(function(){ 
    console.log('in'); 
}); 
+1

OP問編輯動態放置在DOM上的元素,你確定這會起作用嗎? –

+0

是的,這將工作,因爲它適用於一個類。 –

+1

**提示**動態放置 –

相關問題