【问题标题】:jQuery - How to find an index of an ID within another container DIV?jQuery - 如何在另一个容器 DIV 中查找 ID 的索引?
【发布时间】:2013-06-26 02:40:58
【问题描述】:

我想使用 .index,但它似乎不起作用!

<div id="main">
       <div id="one"> 
               <div class="red"> ... </div>
       </div> 
       <div id="two"> 
               <div class="green"> ... </div>
       </div> 
       <div id="three"> 
               <div class="blue"> ... </div>
       </div> 
</div> 

所以我尝试了:

var isDivThere = $("main").index("#two") != -1;

但如前所述,不行......

我怎样才能在 div #main 中简单地查找一个 div?

【问题讨论】:

标签: javascript jquery html dom web


【解决方案1】:
$("#main > div").index($("#two"))

var isDivThere =  $("#main > div").index($("#two")) != -1;

注意:&gt; 仅用于过滤第一级 div。因此,如果您想检查嵌套 div 的索引,我的解决方案将不起作用。

【讨论】:

    【解决方案2】:

    要检查是否存在,您可以这样做:

    var isDivThere = !!$('#two').length;
    

    如果#two必须存在于#main中:

    var isDivThere = !!$('#main').find('#two').length;
    

    如果#two 必须是#main 的孩子:

    var isDivThere = !!$('#main').children('#two').length;
    

    【讨论】:

      【解决方案3】:

      要知道元素在其容器中的索引,只需在您正在寻找的元素 id 上调用 index:

      var isDivThere = $("#two").index();
      

      http://jsfiddle.net/NGhL7/

      【讨论】:

        【解决方案4】:

        您需要添加 # 符号以按 id 进行选择。在这里工作小提琴:

        $("#yourId");
        

        http://jsfiddle.net/nnFh5/

        【讨论】:

          【解决方案5】:

          可以使用jquery的find()函数,

            $("#main").find("#two");
          

          【讨论】:

            【解决方案6】:

            $因为 ID 在整个正文中是唯一的,这足以完成您所做的事情:

            var isDivThere =  !!$$("#two").length;
            

            您将永远不会找到另一个 ID="two" 的元素,因此您无需识别主 div 内的说明

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2023-04-02
              • 2015-08-10
              • 1970-01-01
              • 1970-01-01
              • 2011-12-23
              相关资源
              最近更新 更多