【问题标题】:Why my jquery td click event reacts slow on Chrome?为什么我的 jquery td 点击事件在 Chrome 上反应慢?
【发布时间】:2013-01-04 14:40:07
【问题描述】:

我有一张大桌子(大约 500 行和 7 列)。 我的代码只需要检查我点击的表格单元格(它将类“保留”添加到点击的单元格,这个类做了一些简单的边框操作)。

它在 Firefox 和 Opera 上运行顺畅,但在 Chrome 上却很糟糕(我的意思是我必须等待大约一秒钟才能改变单元格的边框) - 你能建议我解决它的方法吗?

第一个 IF 用于其他一些检查,但它只是检查这个特定单击单元格的状态。

$("td").click( function() 
{
    if($(this).attr('system') !=  1)
    {
        if($(this).attr("reserved") != "1" && $(this).attr("reserved") != "2")
        {
            if($(this).attr("_checked")=="1")
            {
                $(this).addClass("reserved"); // here it changes border color
            }

        }
}

【问题讨论】:

  • 我很好奇为元素设置变量是否有帮助:var td = $(this)
  • 小东西,但你可以把所有的 if 放在一个大语句中,而不是做 sub-if,比如 if($(this).attr('system') != 1 && $(this).attr('reserved') != "1") . . .
  • 另外,如果您使用的是 1.8,您可以查看 $("table").on("click","td", function() {}) 是否提供更好的性能跨度>

标签: jquery css google-chrome optimization


【解决方案1】:

您可以尝试缓存选择器:

$("td").click( function() 
{
    var $this = $(this);

    if($this.attr('system') !=  1)
    {
        if($this.attr("reserved") != "1" && $this.attr("reserved") != "2")
        {
            if($this.attr("_checked")=="1")
            {
                $this.addClass("reserved"); // here it changes border color
            }

        }
}

【讨论】:

  • 我做到了,但不幸的是它没有帮助 - 或者它只做了很小的一部分:) 无论如何,谢谢你的关注!
【解决方案2】:

首先,您可以尝试像这样“压平”这种情况:

$("td").click( function() 
{
    if ($(this).attr('system') != 1 &&
        $(this).attr("reserved") != "1" &&
        $(this).attr("reserved") != "2" &&
        $(this).attr("_checked") == "1")
    {
        $(this).addClass("reserved"); // here it changes border color
    }
}

看看有没有帮助。

【讨论】:

  • 这会使其更具可读性,但不会改变性能。
【解决方案3】:

我建议使用委托事件,因为当必须监视许多元素时,它们的开销要少得多。

$('#yourTableID').on('click', 'td', function(event) {

  .. 

});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-28
    • 2013-07-09
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    • 2013-11-04
    • 1970-01-01
    相关资源
    最近更新 更多