我正在尝试将点击处理程序绑定(bind)到 DOM 上的多个元素。单击后,该元素会在阴影框中加载一些新内容。玩了一会儿代码后,我注意到每次单击时加载时间都在逐渐变长。
我通过禁用除简单的 console.log 之外的所有点击处理程序功能来对此进行测试。即使在此之后,到第 15 次点击时,响应也变得越来越慢。无论我点击了哪个帖子,或者即使内容已经被加载——在第 15 次点击这个“.shadowbox-link”元素时它真的开始变慢。
这是我的点击处理程序:
$j('#content article .shadowbox-link').bind('click', showShadowboxPost);
哪个函数:
var showShadowboxPost = function() {
// Unbind click handler
$j(this).unbind('click', showShadowboxPost);
// Variables for ajax request
var postData = {
'postId': $j(this).attr('data-id'),
'postType': $j(this).attr('data-type'),
'elementId': $j(this).attr('id'),
'prevPost': $j(this).prev().attr('id'),
'nextPost': $j(this).next().attr('id')
};
preFadeIn();
// If content already loaded, avoid ajax request
// The following functions include the fadeIn
if($j(this).children('.single-post').length !== 0) {
preLoadedRequest(this)
} else {
ajaxRequest(postData, this)
}
// Rebind click handler
$j(this).bind('click', showShadowboxPost);
return false;
};
完整文件在这里:http://www.clarkthomasny.com/wp-content/themes/cleanslate/js/shadowbox-post.js
HTML 基本上是这样的:
<div id="content">
<div id="articles">
<article class="shadowbox-link"></article>
<article class="shadowbox-link"></article>
<article class="shadowbox-link"></article>
[etc..]
</div>
</div>
这是它的页面:http://www.clarkthomasny.com/
我尝试了几种不同的调试方法,但我仍然不确定发生了什么,我认为它一定与将点击处理程序绑定(bind)到这么多元素有关吗?几年来我一直在使用 jQuery,但我很困惑,请帮忙。谢谢!
最佳答案
使用 native DOM 处理程序
document.getElementById('anchorID').onclick=function(){/* some code */}
关于javascript - jQuery 单击处理程序在多次单击后运行缓慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18455260/