【问题标题】:How to select a single child element using jQuery?如何使用 jQuery 选择单个子元素?
【发布时间】:2020-11-21 07:22:36
【问题描述】:

使用 jQuery 如何选择单个子元素?我查看了 Traversing API 并且知道我可以像这样选择所有直接子 img 元素:

$(this).children('img');

要选择第一个子 img 元素,我可以使用这样的下标:

$(this).children('img')[0];

但我想我有点惊讶我不能这样做:

$(this).child('img'); // no subscript, returns single element

还是我错过了什么?

【问题讨论】:

    标签: javascript jquery dom-traversal


    【解决方案1】:

    我想你想做的是这样的:

    $(this).children('img').eq(0);
    

    这将为您提供一个包含第一个 img 元素的 jquery 对象,而

    $(this).children('img')[0];
    

    会给你 img 元素本身。

    【讨论】:

    • 请注意,在第一个答案中使用 find 会给你所有后代元素,而 child 只会给你直接子元素。
    【解决方案2】:

    没有。每个 jQuery 函数都返回一个 jQuery 对象,这就是它的工作原理。这是 jQuery 魔法的关键部分。

    如果你想访问底层元素,你有三个选择......

    1. 不要使用 jQuery
    2. 使用[0] 引用它
    3. 扩展 jQuery 来做你想做的事...

      $.fn.child = function(s) {
          return $(this).children(s)[0];
      }
      

    【讨论】:

    • 啊哈!就是这样。我期待 img 元素(试图引用它的 'src' 属性)而不是 jQuery 对象。现在我将使用 'attr()' 来获取 'src' 属性。
    • 也感谢 3)。我可能会考虑这样做。 :)
    • 没有。例如,如果我使用 find("div")[0],我将不会将 div 作为 jQuery 对象。我会得到div 作为 HTMLElement。要将 div 作为 jQuery 对象,必须使用 .eq(0),正如 Greg 下面所说的。
    【解决方案3】:

    也许是这样?

    $('img', this)[0]
    

    【讨论】:

    • 这不一定会选择直接子节点,并且正如接受的答案一样,这将返回元素,而不是 jQuery 对象。
    【解决方案4】:

    您可以使用带有 jQ​​uery 的 CSS 选择器来定位第一个子元素:

    $(this).children('img:nth-child(1)');
    

    如果您想定位第二个子元素,只需将 1 更改为 2:

    $(this).children('img:nth-child(2)');
    

    等等..

    如果要定位更多元素,可以使用 for 循环:

    for (i = 1; i <= $(this).children().length; i++) {
        let childImg =  $(this).children("img:nth-child("+ i +")");
        // Do stuff...
    }
    

    【讨论】:

      【解决方案5】:

      不是jQuery,正如问题所要求的那样,而是本机(即不需要库)我认为更好的工作工具是querySelector 来获取选择器的单个实例:

      let el = document.querySelector('img');
      console.log(el);
      

      对于所有匹配的实例,使用document.querySelectorAll(),或者对于其他元素中的实例,您可以如下链接:

      // Get some wrapper, with class="parentClassName"
      let parentEl = document.querySelector('.parentClassName');
      // Get all img tags within the parent element by parentEl variable
      let childrenEls = parentEl.querySelectorAll('img');
      

      注意以上等价于:

      let childrenEls = document.querySelector('.parentClassName').querySelectorAll('img');
      

      【讨论】:

        【解决方案6】:
        <html>
        <title>
        
            </title>
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <link rel="stylesheet" type="text/css" href="assets/css/bootstrap.css">
        <body>
        
        
        
        
        <!-- <asp:LinkButton ID="MoreInfoButton" runat="server" Text="<%#MoreInfo%>" > -->
         <!-- </asp:LinkButton> -->
        <!-- </asp:LinkButton> -->
        
        <br />
        <asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
        <div>
        <a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
        <div id="parent" class="dataContentSectionMessages" style="display:none">
            <!-- repeater1 starts -->
                <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
                    <ul  >
                        <li ><h6><strong>lorem</strong></h6></li>
                        <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                        <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                        <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                        <li ><h6><strong>Full Service Contracts</strong></h6></li>
                        <li ><h6><strong>Maintenance Contracts</strong></h6></li>
                    </ul>
            <!-- repeater1 ends -->
        </div>
        </div>
        <div>
        <a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
        <div id="parent" class="dataContentSectionMessages" style="display:none">
            <!-- repeater1 starts -->
                <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
                    <ul  >
                        <li ><h6><strong>lorem</strong></h6></li>
                        <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                        <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                        <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                        <li ><h6><strong>Full Service Contracts</strong></h6></li>
                        <li ><h6><strong>Maintenance Contracts</strong></h6></li>
                    </ul>
            <!-- repeater1 ends -->
        </div>
        </div>
        <div>
        <a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
        <div id="parent" class="dataContentSectionMessages" style="display:none">
            <!-- repeater1 starts -->
                <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
                    <ul  >
                        <li ><h6><strong>lorem</strong></h6></li>
                        <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                        <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                        <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                        <li ><h6><strong>Full Service Contracts</strong></h6></li>
                        <li ><h6><strong>Maintenance Contracts</strong></h6></li>
                    </ul>
            <!-- repeater1 ends -->
        </div>
        </div>
        <div>
        <a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
        <div id="parent" class="dataContentSectionMessages" style="display:none">
            <!-- repeater1 starts -->
                <!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
                    <ul  >
                        <li ><h6><strong>lorem</strong></h6></li>
                        <li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
                        <li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
                        <li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
                        <li ><h6><strong>Full Service Contracts</strong></h6></li>
                        <li ><h6><strong>Maintenance Contracts</strong></h6></li>
                    </ul>
            <!-- repeater1 ends -->
        </div>
        </div>
        
        
        
        
        </asp:Repeater>
        
        
        </body>
        <!-- Predefined JavaScript -->
        <script src="jquery.js"></script>
        <script src="bootstrap.js"></script>
        
        <script>
        
         $(function () {
                $('a').click(function() {
                    $(this).parent().children('.dataContentSectionMessages').slideToggle();
                });
            });
        
            </script>
        
        
        </html>
        

        【讨论】:

        • $(function () { $('a').click(function() { $(this).parent().children('.dataContentSectionMessages').slideToggle(); }) ; });此查询将有助于获取父项的子项
        猜你喜欢
        • 1970-01-01
        • 2012-04-12
        • 1970-01-01
        • 1970-01-01
        • 2011-10-17
        • 1970-01-01
        • 2013-09-08
        • 2019-05-15
        • 1970-01-01
        相关资源
        最近更新 更多