jQuery实时执行多次 [英] jquery live executing multiple times
问题描述
我有以下HTML:
<div id="Content">
<div class="MyDiv">...</div>
<div class="MyDiv">...</div>
</div>
由于ajax调用,MyDiv元素被删除并添加了几次.我使用的函数使用.html()函数替换HTML.
The MyDiv elements are removed and added several times as the result of an ajax call. I use the a function that uses the .html() function to replace the HTML.
页面加载后,我执行以下功能:
When the page loads, I execute the following function:
function DynamicHandlers() {
$('#Content .MyDiv').live({
click: function () { .... },
mouseleave: function () { ... }
});
问题在于,单击和mouseleave处理程序的执行时间与更改HTML一样多.最初,我将处理程序与HTML的创建联系在一起,并且每次HTML更新时都会绑定事件.我以为通过将处理程序移至使用.live()的函数,我只需要运行一次,然后就可以设置处理程序了.他们是谁;唯一的问题是它们被执行了多次.
The problem is that the click and mouseleave handlers are executed as many time as I've changed the HTML. I initially had the handlers tied to the creation of the HTML and I'd bind the events each time the HTML was updated. I thought that by moving the handlers to the function that uses the .live(), I only had to run it once and then the handlers would be set for good. Which they are; the only problem is that they get executed multiple times.
我需要进行哪些更改?
谢谢.
推荐答案
将为DOM中与$('#Content .MyDiv')选择器匹配的每个元素调用您的处理程序.我假设在触发事件时,页面上有多个匹配的元素.
Your handler will be invoked for each element in the DOM that matches the $('#Content .MyDiv') selector. I assume that at the time the event is fired there are multiple elements on the page that match.
这篇关于jQuery实时执行多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!