代码之家  ›  专栏  ›  技术社区  ›  Andrew

简单可笑的jQuery可重用函数问题

  •  1
  • Andrew  · 技术社区  · 16 年前

    非常快速的jQuery问题。..

    我有这个功能:

    $(document).ready(function() {
    
      $('a#show1').click(function() {
        $('.item1').toggle(1000);
        return false;
      });
    
      $('a#show2').click(function() {
        $('.item2').toggle(1000);
        return false;
      });
    
      // And it goes on...
    });
    

    show item div,均为唯一且标识为 itemX

    show1 show2 所以它最终基本上是这样的:

    $('a#showX').click(function() {
        $('.itemX').toggle(1000);
        return false;
    });
    
    6 回复  |  直到 16 年前
        1
  •  2
  •   usoban    16 年前
    $("a[id^=show]").click(function(){
     var id = $(this).attr("id");
     var num = id.substring(4);
     $(".item" + num).toggle(1000);
    });
    

    我希望它能起作用,我没有测试它。

        2
  •  1
  •   Keith    16 年前

    //all <a> with class .show-extra
    $('a.show-extra').click(function() {
      //get the next element with the class .show-extra-panel
      $(this).next('.show-extra-panel').toggle(1000);
      return false;
    });
    

    <a href="#" class="format-link show-extra">text</a>
    <div class="info-panel show-extra-panel">extra toggle text</div>
    
        3
  •  1
  •   belugabob    16 年前

    @usoban的方法是正确的——第一个选择器中的“starts with”语法将找到所有“show”项目,无论有多少。您只需调整代码,使其仅提取“id”的数字部分,而不是全部使用,否则它将查找类为“.itemshow1”而不是“.item1”的元素

    $("a[id^=show]").click(function(){
        $(".item" + this.attr("id").substr(4)).toggle(1000);
    });
    

    @Keith还有一个很好的方法——使用类标记“show”元素——这样就不需要标识符的数字部分——然后依靠“item”的相对位置来定位它。

        4
  •  0
  •   Matthew Groves    16 年前

    如果你知道你有多少,你可以使用for循环并附加变量。

    
    for(var i=1;i<=whatever;i++)
    {
         $('a#show' + i).click(function() { // ... etc ... // });
    }
    
        5
  •  0
  •   kgiannakakis    16 年前

    这是一个想法:

    $('a#show1', 'a#show2').click(function() {
        id = ".item" +  this.id.substr(4);
        $(id).toggle(1000);
        return false;
    });
    
        6
  •  0
  •   David Hedlund    16 年前
    $('a[id^=show]').click(function() {
        var id = $(this).attr('id');
        id = id.substring(id.length-1);
        $('.item'+id).toggle(1000);
        return false;
    });
    
    推荐文章