代码之家  ›  专栏  ›  技术社区  ›  Steve Perks

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

  •  2
  • Steve Perks  · 技术社区  · 17 年前

    我正在使用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;
    });
    


    史蒂夫

    4 回复  |  直到 17 年前
        1
  •  4
  •   Owen Ryan Doherty    17 年前

    像这样的怎么样:

    $('#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> <李>

        2
  •  1
  •   Tomalak    17 年前

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

        3
  •  0
  •   ken    17 年前

    我不知道jquery在mootools中是否有类似的功能

    $$('a.clickedItems').addEvent('click', function(e){
      e.preventDefault();
      $('targetedArea').getChildren()[this.getAllPrevious().length].addClass('selected');
    });
    
        4
  •  0
  •   nickf    17 年前
    $('#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;
    });