开发者

jquery closest function not working with addClass

开发者 https://www.devze.com 2023-02-04 04:38 出处:网络
i have problem with the closest function from jquery. i want to make a menu where you can click several items.

i have problem with the closest function from jquery. i want to make a menu where you can click several items. what i want to know is: if someone clicked an already selected item in the menu, is there a selected item in front of the just deseleceted item. i found the closest function which gives back 1 if there is a dom object which matches the selector and 0 if there is non. so i add the class selected for every clicked menu item and remove it when it gets clicked again.

when you click menu_2, then menu_3, then again menu_3 the closest value should be 1 because there is a selected item in front of the one i just deseleceted.

but this is not the result of my little script, maybe you know something?

reg开发者_StackOverflow社区ards, peter

   $('li').click(function()
     {
      if ($(this).hasClass('selected'))
      {
       $(this).removeClass('selected');
       alert($(this).closest('.selected').size());
      }
      else
      {
       $(this).addClass('selected');
      }
   });

  .selected
  {
   background-color: red;
  }

<ul>
<li>menu_1</li>
<li>menu_2</li>
<li>menu_3</li>
<li>menu_4</li>
<li>menu_5</li>
</ul>

this is my structure:

menu_0 <- selected
 menu_0_0
 menu_0_1
 menu_0_2 <- selected
   menu_0_2_0
   menu_0_2_1 <- selected
menu_1
...

now i deselect menu_0_2_1 and the function closest should give me the DOM object menu_0_2, because this is the closest object which has the class "selected" as seen in the example above.


You are getting confused by the purpose of closest():

Get the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree.

If you want to get the siblings too, then use siblings(), if you want the immediate next use next() ..etc:

$(document).ready(function() {
    $('li').click(function() {
        if ($(this).hasClass('selected')) {
            $(this).removeClass('selected');
            alert('Closest: ' + $(this).closest('.selected').length);
            alert('Siblings: ' + $(this).siblings('.selected').length);
        }
        else {
            $(this).addClass('selected');
        }
        return false;
    });
});

Example link. The return false; is important here to prevent the bubble effect!

0

精彩评论

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