草庐IT

javascript - 选择大量复选框并取消/选择它们的最快方法是什么?

coder 2025-02-02 原文

自从我使用 jQuery 1.3+ 以来,除了一个定时测试正在使用它之外。另一个是我在 2000 年发现的普通 javascript。我停止了这条路线,因为它需要大约 150 秒来运行测试。我已经阅读了很多与选择单个元素相关的 jQuery 优化网页。 “#id”是使用它的最佳案例,但现在我遇到了在具有多个复选框列的相当大的表中选中一列中的所有复选框的问题。

我所做的是设置一个页面,创建 20,000 个表格行和两个复选框列。目标是检查第二列,看看花了多长时间,然后取消选中它们,看看花了多长时间。显然我们想要最短的时间。我只使用 IE6 和 7,在我的情况下,我的所有用户都会这样做。

你说 20,000 行?我也是这么说的,但这将要投入生产(不在我的手中),现在改变已经太晚了。我只是想在时钟还剩 1 秒时抛出冰雹玛丽。此外,我了解到 input.chkbox 不是最快的选择器(对于 IE7)! :)

问题是,是否有更好的方法来执行此 jQuery 或其他操作?我希望它能在我的机器上运行不到半秒。

所以你不必重新输入我已经完成的所有废话这是我想出的测试内容:

更新了 2014 年 4 月早上,以包括进一步的计时赛:

<form id="form1" runat="server">
    <div>
        <a href="#" id="one">input[id^='chkbox'][type='checkbox']</a><br />
        <a href="#" id="two">#myTable tr[id^='row'] input[id^='chkbox'][type='checkbox']</a><br />
        <a href="#" id="three">#myTable tr.myRow input[id^='chkbox'][type='checkbox']</a><br />
        <a href="#" id="four">tr.myRow input[id^='chkbox'][type='checkbox']</a><br />
        <a href="#" id="five">input[id^='chkbox']</a><br />
        <a href="#" id="six">.chkbox</a><br />
        <a href="#" id="seven">input.chkbox</a><br />
        <a href="#" id="eight">#myTable input.chkbox</a><br />

        <a href="#" id="nine">"input.chkbox", "tr"</a><br />
        <a href="#" id="nine1">"input.chkbox", "tr.myRow"</a><br />
        <a href="#" id="nine2">"input.chkbox", "#form1"</a><br />
        <a href="#" id="nine3">"input.chkbox", "#myTable"</a><br />

        <a href="#" id="ten">input[name=chkbox]</a><br />
        <a href="#" id="ten1">"input[name=chkbox]", "tr.myRow"</a><br />
        <a href="#" id="ten2">"input[name=chkbox]", "#form1"</a><br />
        <a href="#" id="ten3">"input[name=chkbox]", "#myTable"</a><br />

        <a href="#" id="ten4">"input[name=chkbox]", $("#form1")</a><br />
        <a href="#" id="ten5">"input[name=chkbox]", $("#myTable")</a><br />

        <a href="#" id="eleven">input[name='chkbox']:checkbox</a><br />
        <a href="#" id="twelve">:checkbox</a><br />
        <a href="#" id="twelve1">input:checkbox</a><br />
        <a href="#" id="thirteen">input[type=checkbox]</a><br />

        <div>
            <input type="text" id="goBox" /> <button id="go">Go!</button>
            <div id="goBoxTook"></div>
        </div>

        <table id="myTable">
            <tr id="headerRow"><th>Row #</th><th>Checkboxes o' fun!</th><th>Don't check these!</th></tr>
            <% for(int i = 0; i < 20000;i++) { %>
            <tr id="row<%= i %>" class="myRow">
                <td><%= i %> Row</td>
                <td>
                    <input type="checkbox" id="chkbox<%= i %>" name="chkbox" class="chkbox" />
                </td>
                <td>
                    <input type="checkbox" id="otherBox<%= i %>" name="otherBox" class="otherBox" />
                </td>
            </tr>
            <% } %>
        </table>
    </div>

    <script type="text/javascript" src="<%= ResolveUrl(" ~/") %>Javascript/jquery.1.3.1.min.js"></script>
    <script type="text/javascript">

        $(function () {
            function run(selectorText, el) {
                var start = new Date();
                $(selectorText).attr("checked", true);
                var end = new Date();
                var timeElapsed = end - start;
                $(el).after("<br />Checking Took " + timeElapsed + "ms");

                start = new Date();
                $(selectorText).attr("checked", false);
                end = new Date();
                timeElapsed = end - start;
                $(el).after("<br />Unchecking Took " + timeElapsed + "ms");
            }

            function runWithContext(selectorText, context, el) {
                var start = new Date();
                $(selectorText, context).attr("checked", true);
                var end = new Date();
                var timeElapsed = end - start;
                $(el).after("<br />Checking Took " + timeElapsed + "ms");

                start = new Date();
                $(selectorText, context).attr("checked", false);
                end = new Date();
                timeElapsed = end - start;
                $(el).after("<br />Unchecking Took " + timeElapsed + "ms");
            }

            $("#one").click(function () {
                run("input[id^='chkbox'][type='checkbox']", this);
            });

            $("#two").click(function () {
                run("#myTable tr[id^='row'] input[id^='chkbox'][type='checkbox']", this);
            });

            $("#three").click(function () {
                run("#myTable tr.myRow input[id^='chkbox'][type='checkbox']", this);
            });

            $("#four").click(function () {
                run("tr.myRow input[id^='chkbox'][type='checkbox']", this);
            });

            $("#five").click(function () {
                run("input[id^='chkbox']", this);
            });

            $("#six").click(function () {
                run(".chkbox", this);
            });

            $("#seven").click(function () {
                run("input.chkbox", this);
            });

            $("#eight").click(function () {
                run("#myTable input.chkbox", this);
            });

            $("#nine").click(function () {
                runWithContext("input.chkbox", "tr", this);
            });


            $("#nine1").click(function () {
                runWithContext("input.chkbox", "tr.myRow", this);
            });
            $("#nine2").click(function () {
                runWithContext("input.chkbox", "#form1", this);
            });
            $("#nine3").click(function () {
                runWithContext("input.chkbox", "#myTable", this);
            });

            $("#ten").click(function () {
                run("input[name=chkbox]", this);
            });

            $("#ten1").click(function () {
                runWithContext("input[name=chkbox]", "tr.myRow", this);
            });

            $("#ten2").click(function () {
                runWithContext("input[name=chkbox]", "#form1", this);
            });

            $("#ten3").click(function () {
                runWithContext("input[name=chkbox]", "#myTable", this);
            });

            $("#ten4").click(function () {
                runWithContext("input[name=chkbox]", $("#form1"), this);
            });

            $("#ten5").click(function () {
                runWithContext("input[name=chkbox]", $("#myTable"), this);
            });

            $("#eleven").click(function () {
                run("input[name='chkbox']:checkbox", this);
            });

            $("#twelve").click(function () {
                run(":checkbox", this);
            });

            $("#twelve1").click(function () {
                run("input:checkbox", this);
            });

            $("#thirteen").click(function () {
                run("input[type=checkbox]", this);
            });

            $('#go').click(function () {
                run($('#goBox').val(), this);
            });
        });
    </script>
</form>

最佳答案

input[name=chkbox] 是我机器上 IE7 下最快的 jQuery 选择器。

Unchecking Took 2453ms
Checking Took 2438ms
Unchecking Took 2438ms
Checking Took 2437ms
Unchecking Took 2453ms
Checking Took 2438ms

input.chkbox 和...

Unchecking Took 2813ms
Checking Took 2797ms
Unchecking Took 2797ms
Checking Took 2797ms
Unchecking Took 2813ms
Checking Took 2797ms

input:checkbox.chkbox 似乎绑定(bind)

Unchecking Took 2797ms
Checking Took 2797ms
Unchecking Took 2813ms
Checking Took 2781ms

.chkbox 几乎是 input.chkbox 的两倍

Unchecking Took 4031ms
Checking Took 4062ms
Unchecking Took 4031ms
Checking Took 4062ms

javascript for 循环是迄今为止最糟糕的出现在:

Checking Took 149797ms

150 秒!它也锁定了浏览器。这让我对 jQuery 印象深刻。老实说,我没想到会这么慢。可能是因为我传递了它必须找到的每个单独的元素......

这对我来说也很有趣:

输入[id^='chkbox']

Unchecking Took 3031ms
Checking Took 3016ms

花费的时间少于:

输入[id^='chkbox'][type='checkbox']

Unchecking Took 3375ms
Checking Took 3344ms

我想既然我发布了更多的过滤器,它会更快。不!

为复选框指定更多路径会使速度变慢:

#myTable tr[id^='row'] input[id^='chkbox'][type='checkbox']

Checking Took 10422ms

它甚至没有运行第二次取消检查,因为它询问我是否要继续在我的计算机上运行脚本。疯狂的! :P

4 月 14 日上午更新:

有人提出设置上下文:我实际上做了其中的一些,这让我大吃一惊,而且与很多人在网络上所说的在 IE7 上这些速度较慢相反!以下是我使用几个不同的上下文指定的时间与上面更快的选择器配对:

"input.chkbox", "tr"

Checking Took 8546ms

"input.chkbox", "tr.myRow"

Checking Took 8875ms

"input.chkbox", "#form1"

Unchecking Took 3032ms
Checking Took 3000ms

"input.chkbox", "#myTable"

Unchecking Took 2906ms
Checking Took 2875ms

当前获胜者(仍然):input[name=chkbox]

Unchecking Took 2469ms
Checking Took 2453ms

"输入[name=chkbox]", "tr.myRow"

Checking Took 9547ms

"输入[name=chkbox]", "#form1"

Unchecking Took 3140ms
Checking Took 3141ms

"输入[name=chkbox]", "#myTable"

Unchecking Took 2985ms
Checking Took 2969ms

2 月 4 日上午更新 2

在我注意到与 http://beardscratchers.com/journal/jquery-its-all-about-context 的语法差异后,我想我可能会有一个更好的.看起来这些与它们给出的时间稍微好一些,但仍然没有击败非上下文选择器 - 该死的。

"输入[name=chkbox]", $("#form1")

Unchecking Took 3078ms
Checking Took 3000ms
Unchecking Took 3078ms
Checking Took 3016ms

"输入[name=chkbox]", $("#myTable")

Unchecking Took 2938ms
Checking Took 2906ms
Unchecking Took 2938ms
Checking Took 2921ms

4 月 14 日上午更新 3

Russ 想让我试试这些,他们取消/选择了所有框,但这又很有趣:

:复选框

Unchecking Took 8328ms
Checking Took 6250ms

输入:复选框

Unchecking Took 5016ms
Checking Took 5000ms

->最快?!?! 输入[type=checkbox]

Unchecking Took 4969ms
Checking Took 4938ms

第三个是最快的这一事实非常有趣,因为这与我的想法相反。为什么(至少对于 IE7) :checkbox 不使用 type=checkbox 来获得更快的时间?这些分数非常接近,但检查时间减少了 62 毫秒。另外,为什么前两个完全不同?除了可以带复选框的输入之外,是否还有其他元素?

关于javascript - 选择大量复选框并取消/选择它们的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/745720/

有关javascript - 选择大量复选框并取消/选择它们的最快方法是什么?的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  5. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  6. Ruby 方法() 方法 - 2

    我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby​​-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco

  7. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  8. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  9. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  10. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

随机推荐