【问题标题】:After clicking the nth item, how do I manipulate another nth element?单击第 n 个元素后,如何操作另一个第 n 个元素?
【发布时间】:2010-09-20 14:04:39
【问题描述】:

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

    我可以单独定位它们,但我知道通过传递我单击的 元素必须有更快的方法。

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

    干杯,
    史蒂夫

  • 【问题讨论】:

      标签: javascript jquery


      【解决方案1】:

      这样的事情怎么样:

      $('#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;
      });
      

      假设您的 &lt;a&gt;&lt;li&gt; 元素之间存在 1:1 的关系,它将更新相应的 &lt;li&gt;

      【讨论】:

        【解决方案2】:

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

        为每个 A 和 LI 元素指定一个 ID,并制作这些 ID,以便您可以相互推断它们。只要点击一个A,你立即知道LI的ID并且可以直接引用它。

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

        【讨论】:

          【解决方案3】:

          我不知道 jquery 在 mootools 中是否有类似的东西

          $$('a.clickedItems').addEvent('click', function(e){
            e.preventDefault();
            $('targetedArea').getChildren()[this.getAllPrevious().length].addClass('selected');
          });
          

          【讨论】:

            【解决方案4】:
            $('#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;
            });
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2012-07-09
              • 1970-01-01
              • 2021-10-03
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2019-09-16
              • 2016-04-10
              相关资源
              最近更新 更多