[英]How to make JS framework custom functions work for dynamically added elements?
[英]how to make jquery functions work with dynamically changing elements
首先讓我說我看過這篇文章 。
這說明(與api.jquery.com一樣 ) ,. live .live()
和.on()
允許您分配一個jquery事件,該事件甚至適用於將來的元素。 但是我下面的jQuery:
$("#playerImg").on("mouseenter",function () {
console.log("works");});
在開始時有效,但在我運行以下代碼后:
function move(moveTo) {
document.getElementById(player.currentLocation).innerHTML = "";
player.currentLocation = moveTo;
document.getElementById(player.currentLocation).innerHTML += player.displayText;
}
這是相關的變量
var player = {
"displayText" : "<img src = 'http://3.bp.blogspot.com/-kAhN0HX-MBk/T_5bApfhbJI/AAAAAAAAAuI/lUww8xT9yV8/s1600/smileys_001_01.png'" +
id='playerImg' "class='onTop' alt='you' border='0' />",
"currentLocation": 0 //(i use a 5 * 5 table with id's 0-24)
}
上面的代碼沒有運行。 我如何在jquery中創建一個事件,該事件可以在尚不存在的元素上運行?
使用.on()
像你這樣直接申請的事件,這是速度更快,但並不適用於動態元素。
您需要使用.on()
這樣的動態元素:
$(document).on("mouseenter", '#playerImg',function () {
console.log("works");
});
document
應該是獲取性能最接近的靜態元素。
注意, id
必須是唯一的,請更改class
。 上面的代碼可能無法使用,因為它使用了ID。 如果是這種情況,並且您不想出於任何原因進行更改,請使用以下命令:
$(document).on("mouseenter", 'img#playerImg',function () {
console.log("works");
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.