单击第n个项目后,如何操作另一个第n个元素

After clicking the nth item, how do I manipulate another nth element?

本文关键字:操作 元素 另一个 项目 单击 何操作      更新时间:2023-09-26

我正在使用jQuery,并希望将第n个<李>在单击第n个链接后的列表中。

<ul id="targetedArea">
  <li></li>
  <li></li>
  <li></li>
  <li></li>
</ul>
<div id="clickedItems">
  <a></a>
  <a></a>
  <a></a>
  <a></a>
</div>

我可以单独针对他们,但我知道必须有一种更快的传球方式<a>我点击的元素。

$("#clickedItem a:eq(2)").click(function() {
  $("#targetedArea:eq(2)").addClass('active');
  return false;
});

干杯,
Steve

这样的东西怎么样:

$('#clickedItems a').click(function() {
// figure out what position this element is in
   var n = $('#clickedItems a').index($(this) );
// update the targetedArea
   $('#targetedArea li:eq('+n+')').html('updated!');
   return false;
});

假设<a><li>元素之间的关系为1:1,它将更新相应的<li>

我知道这并不能直接回答你的问题,但也许你让它变得更难了。

给A和LI元素中的每个元素一个ID,并制作这些ID,以便您可以从彼此推断它们。一旦点击A,你就会立即知道李的ID,并可以直接引用它。

作为一个副作用,这比任何可能做同样事情的聪明jQuery都更有效率。

我不知道jquery在mootools 中是否有这样的东西

$$('a.clickedItems').addEvent('click', function(e){
  e.preventDefault();
  $('targetedArea').getChildren()[this.getAllPrevious().length].addClass('selected');
});
$('#clickedItems a').click(function() {
    // you probably want to turn off the currently active one
    $('#targetedArea li.active').removeClass("active");
    // count the links previous to this one and make the corresponding li active
    $('#targetedArea li:eq(' + $(this).prevAll('a').length + ')').addClass("active");
    // prevent the browser from going to the link
    return false;
});