【问题标题】:How to find a particular Div using jQuery如何使用 jQuery 查找特定的 Div
【发布时间】:2011-11-10 00:32:42
【问题描述】:

请指导我如何使用 jQuery 找到特定的 div 来跟踪 html -

       <div class="tab_container">
            <div id="tabs-1111" class="tab_content" style="display: block;">
                <p>26 High Street, Slough, SL1 1EP</p>
                <p></p>
            </div>
            <div id="tabs-1110" class="tab_content" style="display: none;">
                <p></p>
                <p></p>
                <div id="GoogleMap_Canvas" 
                    style="width: 410px; height: 450px; position: relative; overflow: hidden;">
                    <p></p>
                </div>
            </div>    
        </div>

我想检查具有“tab_content”类的第一个 div 是否包含 id = 'GoogleMap_Canvas' 的 div - 对于上面的 html,这应该是错误的,因为它在第二个 div 中。

我尝试使用 -

if ($(".tab_content:first").children('#GoogleMap_Canvas').length > 0)
or
if ($(".tab_content:nth-child(1)").children('#GoogleMap_Canvas').length> 0)

这对我来说似乎工作得很好。

但是,我很困惑为什么跟随 jQuery 返回 null?

($(".tab_content")[1]).children('#GoogleMap_Canvas') //returns null

谢谢!

【问题讨论】:

    标签: jquery


    【解决方案1】:

    由于您正在检查一个唯一的 id,这不需要那么复杂。

    if ($('#GoogleMap_Canvas').length > 0)
      //map div exists
    

    我相信你得到一个 null 因为你在一个非 jquery 对象上调用 .children 。试试这个:

    $($(".tab_content")[1]).children('#GoogleMap_Canvas')
    

    或更好:

    $(".tab_content:eq(1)").children('#GoogleMap_Canvas')
    

    【讨论】:

      【解决方案2】:

      您可以尝试使用 jQuery 的 has selector 来获取包含“GoogleMap_Canvas”div 的“tab_content”div:

      var googleDivContainer = $(".tab_content").has('#GoogleMap_Canvas');
      

      【讨论】:

        【解决方案3】:

        这将返回 NULL

        ($(".tab_content")[1]).children('#GoogleMap_Canvas')
        

        因为 $(".tab_content")[1] 返回一个没有子方法的 DOM 元素。

        添加额外的“$”以将结果转换为 jQuery 对象

        $($(".tab_content")[1]).children('#GoogleMap_Canvas')
        

        【讨论】:

          【解决方案4】:

          “我想检查第一个具有 'tab_content' 类的 div 是否包含 id = 'GoogleMap_Canvas' 的 div”

          使用这个:

          if ($(".tab_container").children('.tab_content:first').children('#GoogleMap_Canvas').length > 0){
          // do something
          }
          

          【讨论】:

            【解决方案5】:

            您的最后一行返回 null,因为 $(".tab_content")[1] 返回一个 DOM 元素,而不是 jQuery 对象,并且 DOM 元素不公开 children() 方法。

            注意eq() 返回一个 jQuery 对象,所以下面的代码可以工作:

            var children = $(".tab_content").eq(1).children('#GoogleMap_Canvas');
            

            【讨论】:

              【解决方案6】:

              试试这个:

              var length = $(".tab_content[id*='GoogleMap_Canvas']").length;
              

              【讨论】:

                猜你喜欢
                • 2021-12-16
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2011-03-23
                • 1970-01-01
                • 2012-05-27
                相关资源
                最近更新 更多