新加载的jquery .load元素不响应.on事件

时间:2014-03-06 00:25:42

标签: jquery

我有JQUERY动态加载(.load)一段代码。它有按钮,应该响应以下内容:

$(":button").on('mouseout mouseover', ETC... );

这些新加载的按钮不会继承mouseout鼠标悬停事件。我怎样才能解决这个问题?我尝试在加载的元素中重复使用代码,但后来我将鼠标悬停在旧的加载元素上。

2 个答案:

答案 0 :(得分:1)

$(document).on('mouseout mouseover', ':button', function () { /*...*/ });

答案 1 :(得分:1)

对于那些寻找这个答案的人来说,问题是你不能将事件附加到你尚未创建的元素(例如,你通过ajax动态加载)。

简单的解决方案是在容器元素上侦听事件。这是event delegation的一项功能。

当其中一个动态元素(例如点击)发生事件时,事件会通过DOM树冒泡,让每个父母都有机会倾听并对该事件做出反应。

示例HTML:

<div id="container"></div>

示例JS:

// Populate container dynamically (could be via AJAX)
$('#container').html('<button class="button">Dynamic Button</button>');

$('#container').on('click', '.button', function() {
   // This attaches the listener to a container element.
   // When the child '.button' element is clicked the event will bubble up and
   // we can handle it here.
});

$(document).on('click', '.button', function() {
   // This one is bound at the document level and will also fire unless
   // an listener stops the propagation. It would fire last.
});

那么你应该把你的听众连接到哪一个?如果你有一个持久的容器,那么将监听器连接到容器(而不是一直在document的顶部)是更有效的,因为它可以更快地处理(减少冒泡)。

相关问题