0

I am using Backbone here, but I've also experienced this issue with non-Backbone sites as well.

Essentially, my issue is that I define in one javascript file, base.js, a number of 'global' jquery functions. Then, I load new elements and append them to the page using Backbone, AJAX, or whichever asynchronous call you like. This works great, except the new objects don't seem to be linked to the jQuery events I declared on pageload. (Sorry for the layman language here - often I am a newbie at proper wording)

For example, let's say I declare in a js file loaded on pageload:

 $('.element').hover(function(){alert('hi world')});

But then I append a new element after pageload, then this hover won't work.

Can anyone explain:

  1. Why this is?
  2. Whether I can force a new appended element to work with/listen to current events already declared?

I suspect (2) may not be possible (that I have to rewrite the events after appending), but am interested to know if there is some sort of solution.

4

1 回答 1

5

这是为什么?

因为当事件绑定代码被执行时,DOM中已经不存在的元素不会受到影响(它们怎么可能呢?它们还不存在!)“正常”的事件绑定方法(例如.click()or .change())将附加一个将事件处理函数复制到匹配集中的每个元素。

我可以强制一个新的附加元素使用/收听已经声明的当前事件吗?

您确实可以通过将事件处理程序委托给 DOM 树的更高层。由于大多数 DOM 事件从它们起源的元素开始在树中冒泡,因此效果很好。使用 jQuery,您可以使用.on()(jQuery 1.7+ - 用于旧版本.delegate()) 方法来执行此操作:

$("#someCommonAncestor").on("someEvent", ".element", function () {
    // Do stuff
});

在代码运行时,您调用的元素.on()必须存在于 DOM 中。当事件冒泡足够远以达到任何#someCommonAncestor可能时,jQuery 将检查目标元素是否与您传递给的选择器匹配.on()。如果是,它将执行事件处理程序。如果没有,该事件将继续冒泡到文档的根目录,并且不会触发任何处理程序。

于 2012-12-06T15:30:34.587 回答