如何使jquery函数与动态变化的元素一起工作

how to make jquery functions work with dynamically changing elements

本文关键字:元素 一起 工作 变化 动态 何使 jquery 函数      更新时间:2023-09-26

首先让我说我看过这篇文章。

它说(和api.jquery.com一样).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");
});