开发者

jQuery index() returning the same value after dynamic change in list

开发者 https://www.devze.com 2023-03-18 07:56 出处:网络
i have the following piece of HTML <开发者_运维技巧;a id=\"zoom\" href=\"...\">zoom current artwork</a>

i have the following piece of HTML

<开发者_运维技巧;a id="zoom" href="...">zoom current artwork</a>

<div id="album-artwork">
   <ul>
      <li><a class="current">image 1</a></li>
      <li><a>image 2</a></li>
      <li><a>image 3</a></li>
      <li><a>image 4</a></li>
      <li><a>image 5</a></li>
   </ul>
</div>

when i click the link with the id 'zoom', i want to get the index in the 'album-artwork' list that contains the tag 'a' with the class 'current'. So i did the following in jQuery and it works perfectly!

// ZOOM artwork
$("#zoom").click(function(e) {

   // highlight
   var index = $('#album-artwork ul li a.current').index();
   alert(index);

   e.preventDefault();
}

Now, this is were it doesn't work! When i run another jQuery code to change the class in the tag 'a' in 'album-artwork'... like this:

$('#album-artwork a').click(function(e) {   

   // add decoration
   $("#album-artwork a").removeClass('current');
   $(this).addClass("current");

   e.preventDefault();
});

the previous code, the one that gets the index with the tag 'a' with a class 'current', keeps returning the same value... as if it doesn't see that i've just the change the class 'current' in the tag 'a'

Why is that? How come it doesn't see the changes?

Thanks


You are querying the hierarchy the wrong way: The a tag is always the first (and only) descendant of the enclosing li, hence the index 0 is always correct. Just don't query the a but query the li directly:

<div id="album-artwork">
  <ul>
    <li>image 1</li>
    <li>image 2</li>
    <li>image 3</li>
    <li>image 4</li>
    <li class="current">image 5</li>
  </ul>
</div>

And for the JavaScript:

$("#zoom").click(function(e) {
  var index = $('#album-artwork ul li.current').index();
  alert(index);
  e.preventDefault();
});
$('#album-artwork li').click(function(e) {   
  $("#album-artwork li").removeClass('current');
  $(this).addClass("current");
  e.preventDefault();
});


The <a> tag in your case is the first element inside the <li> tag, so .index() is returning a correct value: 0. You have to use the <li> tag to get what you want. So you can either use .addClass('current') on the <li> tag, or use .parent() on <a> tag like that:

$("#zoom").click(function(e) {
    var index = $('#album-artwork ul li a.current').parent().index();
    alert(index);
    return false;
});
$('#album-artwork a').click(function(e) {   
    // add decoration
    $("#album-artwork a").removeClass('current');
    $(this).addClass("current");
    return false;
});
0

精彩评论

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

关注公众号