javascript - jQuery 单击处理程序在多次单击后运行缓慢

标签 javascript jquery performance event-handling click

我正在尝试将点击处理程序绑定(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/

相关文章:

linq - 使用 DefaultIfEmpty 改进 Linq 子查询

javascript - 创建一个自动检测颜色格式(rgb 或 hex)的函数,并将其分别转换为 hex 或 rgb

javascript - 如何使用 jQuery 查找行 ID?

javascript - 在外部标签上追加/前置空格

javascript - 我如何检查 '.classname' 项目有多少?

jquery - 如何使 ul 之前的文本在 html 中以单行显示?

java - 如何编写 Java 代码以允许使用 SSE 和边界检查消除(或其他高级优化)?

javascript - let 语句应用后果

javascript - 为什么我的 Angular 代码返回未定义?

javascript - 最持久的 HTML5 数据存储是什么?