jQuery click类事件触发多次单击 [英] JQuery click class event triggers multiple clicks
问题描述
我有许多图像类为"more-info"的图像项,这些图像项应响应click事件并将ajax内容加载到div,但这是第一次找到,但是当我单击任何其他图像作为第二次触发2次点击,第三次触发3次,依此类推.
I have a number of image items with class 'more-info' that should respond to click event and load ajax content to a div, however this works find for the first time, but when I click in any other image for the second time, it triggers 2 clicks for third time it triggers 3 clicks and so on.
这是html:
<div id="test" style="display:none"></div>
<div class="image-item">
<img class="more-info" src="/site/uploads/documents/_thumb01.jpg" path="/site/auto/1" />
</div>
<div class="image-item">
<img class="more-info" src="/site/uploads/documents/_thumb02.jpg" path="/site/auto/2" />
</div>
<div class="image-item">
<img class="more-info" src="/site/uploads/documents/_thumb03.jpg" path="/site/auto/4" />
</div>
还有ajax处理程序:
And ajax handdler:
$(function () {
$('.more-info').click(function(event) {
event.preventDefault()
url = $(this).attr('path');
$('#test').load(url, function(){
alert('loaded: '+ url)
})
})
});
推荐答案
我认为您正在重新加载包括javascript在内的整个html页面.因此,每次点击都会添加另一个事件处理程序.
I think you are loading an entire html page again including the javascript. So for each click you will have another event handler added.
因此,除了加载整个页面,您只能加载页面的特定部分:
So instead of loading the entire page you could only load a specific part of the page:
$('#test').load(url + ' #somediv', function(){
请参阅文档中的 jQuery的加载示例.
或者您应该确保请求的结果仅包含所需的部分.
Or you should just make sure the result of the request only contains the part you need.
最后一种可能的解决方案是在加载内容之前.unbind()
该事件:
One last possible solution would be to .unbind()
the event before loading the content:
$(function () {
$('.more-info').click(function(event) {
event.preventDefault();
// for caching the element, because it will be referenced twice
var $elem = $(this);
url = $elem.attr('path');
$elem.unbind('click');
$('#test').load(url, function() {
// used console.log which is cleaner imho
console.log('loaded: '+ url);
});
});
});
这篇关于jQuery click类事件触发多次单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!