开发者

jQuery: Selecting a link one level up from a lower level link

开发者 https://www.devze.com 2023-03-21 17:05 出处:网络
I\'m working with an unordered list of links that has two levels: <ul class=\"level-1\"> <li class=\"item-a\"><a href=\"#\">A</a></li>

I'm working with an unordered list of links that has two levels:

   <ul class="level-1">
      <li class="item-a"><a href="#">A</a></li>
      <li class="item-b"><a href="#">B</a>
        <ul class="level-2">
          <li class="item-1"><a href="#">1</a></li>
          <li 开发者_如何学运维class="item-2"><a href="#">2</a></li>
          <li class="item-3"><a href="#">3</a></li>
        </ul>
      </li>
      <li class="item-c"><a href="#">C</a></li>
    </ul>

I click one of the .level-2 links, and want to select the higher level link from the list that contains the clicked link. (For example, I click either 1, 2, or 3 - and I want to select B.)

If my clicked link is selected as $(this).find('a') -- how can I select the higher level link?

Would appreciate your advice!


One way would be to go up to the closest <ul>, then up again to the closest <li>, and then back down to the <a>:

$('a').click(function() {
    var $a = $(this).closest('ul').closest('li').find('a:first');
    // $a is the <a> you want.
});

This approach is fairly flexible and not overly dependent on your DOM structure, you'd be able to add things before or after the <a> you want without breaking your code (unless of course you started adding <li>s or <ul>s).

There are certainly other ways to do this but the above is pretty simple and straight forward and that should be your second concern (your first being that it works).

Referenences:

  • closest
  • find
  • :first


Use a combination of the closest and find functions (API references here and here):

 $(this).closest('ul')
        .closest('li')
        .find('a')
        .text() // Equals B if 1, 2, or 3 are clicked. 
                // Equals '' if A, B, or C are clicked.

Here's a jsFiddle: http://jsfiddle.net/FishBasketGordo/nmunm/


You can use this:

$(document).ready(function() {
    $("ul.level-2 a").click(function () {
       alert($(this).closest('ul.level-2').parent().find('a').html()); 
    });
});

Look the sample working: http://jsfiddle.net/znHXK/


for your reference

$(function(){
    $("a").each(function(){
        $(this).click(function(){
            $(this).css("background-color","red");
            $(this).parents("li").children("a").css("background-color","blue");
        });
    })
})
0

精彩评论

暂无评论...
验证码 换一张
取 消