jQuery: get parent, parent id?

后端 未结 3 1077
离开以前
离开以前 2020-12-02 21:44

How can I get the id of the ul (myList)

相关标签:
3条回答
  • 2020-12-02 22:25
     $(this).closest('ul').attr('id');
    
    0 讨论(0)
  • 2020-12-02 22:31
    $(this).parent().parent().attr('id');
    

    Is how you would get the id of the parent's parent.

    EDIT:

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

    Is a more foolproof solution for your case.

    0 讨论(0)
  • 2020-12-02 22:38

    Here are 3 examples:

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

    Let me know whether it was helpful.

    0 讨论(0)
提交回复
热议问题