itsource

jQuery: 부모, 부모 ID를 가져오시겠습니까?

mycopycode 2023. 9. 4. 19:47
반응형

jQuery: 부모, 부모 ID를 가져오시겠습니까?

<ul id ="myList">
<li><a href="www.example.com">link</a></li>
</ul>

jQuery를 사용하여 ul(myList)의 ID를 얻으려면 어떻게 해야 합니까?링크를 클릭하면 내 j-script 이벤트가 트리거됩니다.시도해 본 결과:

$(this).parent().attr('id');

하지만 그것은 리의 아이디를 얻었고, 저는 한 단계 더 올라가야 하고, 클릭도 리에 붙일 수 없습니다.

$(this).parent().parent().attr('id');

부모님의 신분증을 얻는 방법입니다.

편집:

$(this).closest('ul').attr('id');

귀하의 경우에 더욱 완벽한 솔루션입니다.

 $(this).closest('ul').attr('id');

다음은 3가지 예입니다.

$(document).on('click', 'ul li a', function (e) {
    e.preventDefault();

    var example1 = $(this).parents('ul:first').attr('id');
    $('#results').append('<p>Result from example 1: <strong>' + example1 + '</strong></p>');

    var example2 = $(this).parents('ul:eq(0)').attr('id');
    $('#results').append('<p>Result from example 2: <strong>' + example2 + '</strong></p>');
  
    var example3 = $(this).closest('ul').attr('id');
    $('#results').append('<p>Result from example 3: <strong>' + example3 + '</strong></p>');
  
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id ="myList">
  <li><a href="www.example.com">Click here</a></li>
</ul>

<div id="results">
  <h1>Results:</h1>
</div>

도움이 되었는지 알려주세요.

언급URL : https://stackoverflow.com/questions/10260667/jquery-get-parent-parent-id

반응형