programing tip

jQuery를 사용하여 단일 자식 요소를 선택하는 방법은 무엇입니까?

itbloger 2020. 12. 11. 07:55
반응형

jQuery를 사용하여 단일 자식 요소를 선택하는 방법은 무엇입니까?


jQuery를 사용하여 단일 자식 요소를 어떻게 선택합니까? Traversing API를 살펴본 결과 img다음과 같은 모든 직계 자식 요소를 선택할 수 있다는 것을 알고 있습니다 .

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

첫 번째 자식 img요소 를 선택하기 위해 다음 과 같은 첨자를 사용할 수 있습니다.

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

그러나 나는 이것을 할 수 없다는 것에 약간 놀랐습니다.

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

아니면 내가 놓친 것이 있습니까?


아니오. 모든 jQuery 함수는 jQuery 객체를 반환하며 이것이 작동하는 방식입니다. 이것은 jQuery의 마법의 중요한 부분입니다.

기본 요소에 액세스하려면 세 가지 옵션이 있습니다.

  1. jQuery를 사용하지 마십시오
  2. [0]그것을 참조하기 위해 사용
  3. jQuery를 확장하여 원하는 작업을 수행하십시오.

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

나는 당신이 원하는 것은 이것이라고 생각합니다.

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

그러면 첫 번째 img 요소를 포함하는 jquery 객체가 제공되지만

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

img 요소 자체를 제공합니다.


아마도 이런 식으로?

$('img', this)[0]

<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>

아니 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
let childrenEls = parent.querySelectorAll('img');

위의 내용은 다음과 같습니다.

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

참고 URL : https://stackoverflow.com/questions/1474089/how-to-select-a-single-child-element-using-jquery

반응형