【问题标题】:jQuery - hide all elements except first onejQuery - 隐藏除第一个元素以外的所有元素
【发布时间】:2012-05-14 19:09:06
【问题描述】:

假设我有 10 个按钮。我想隐藏除第一个按钮之外的所有按钮。

我试图在 jQuery 中使用 each() 来完成它,但它不起作用。

这是我的脚本。这只是一个测试,看看我是否可以获得按钮的索引。没有出现错误。

$('button').each(function(index){
    alert(index);
});

附加信息:

我的整个脚本是这样的

$(function(){
   $('div#here').load('test.php'); // This is where all the buttons will come from
   $('button').each(function(index){
       alert(index);
   });
});

【问题讨论】:

    标签: jquery loops each


    【解决方案1】:

    试试这个:

    Slice() 提供更好的性能

    $('button').slice(1).hide();
    

    【讨论】:

      【解决方案2】:

      与 ThiefMaster 相同,但不要忘记您需要等待按钮加载。

      你需要使用 load 的回调:

      $(function(){
      $('div#here').load('test.php', function(){
         $('button:not(:first)').hide();
      }); // This is where all the buttons will come from
      
      });
      

      文档:http://api.jquery.com/load/

      【讨论】:

      • 谢谢!我结合了你的答案和编码器的。如果可以的话,我会给你们两个正确的答案。
      【解决方案3】:

      使用其中一种:

      $('button:not(:first)').hide();
      $('button:gt(0)').hide();
      

      【讨论】:

        猜你喜欢
        • 2013-09-23
        • 2015-06-18
        • 2023-03-29
        • 1970-01-01
        • 2011-05-15
        • 2012-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多