jQuery ID号范围

我正在尝试编写一个jQuery脚本,它将添加一个类来列出特定ID范围内的项目。 我在我的ID中使用数字,并希望调整ID的范围。

  • Something
  • Something
  • Something
  • Something
  • Something
  • 我想添加一个类来说明第16到19项。我该怎么做?

     jQuery('li#item-[16-19]).addClass('the-class'); 

    我不确定该怎么做。 也许.each()

    这就是jquery .slice()方法的目的。

    给定一个表示一组DOM元素的jQuery对象,.slice()方法从匹配元素的子集构造一个新的jQuery对象。 提供的起始索引标识集合中某个元素的位置; 如果省略end,则此结束后的所有元素都将包含在结果中。

    所以

     jQuery('li').slice(17,21).addClass('the-class'); //note Zero Based indexing. Plus it wont include the last element. 

    实例: http : //jsfiddle.net/VpNnJ/

    您还可以将:gt()和:lt()选择器组合如下

    $('li:gt(16):lt(19)').addClass('the-class');

    再一个现场的例子: http : //jsfiddle.net/cLjXE/

     var min = 16, max = 19; $('li[id^=item-]').addClass(function () { var i = parseInt(this.id.replace('item-', ''), 10); if (i >= min && i <= max) return 'the-class'; }); 

    为了特异性,您可能应该使用公共父级限定选择器,例如

     $('#some-ul-id > li[id^=item-]').addClass(...); 

    如果ID总是按顺序递增,并且零索引,则可以简化:

     $('#some-ul-id > li[id^=item-]').addClass(function (i) { if (i >= min && i <= max) return 'the-class'; }); 

    或者,正如@matchew建议的那样 ,使用.slice()

     $('#some-ul-id > li[id^=item-]').slice(min, max).addClass('the-class'); 
     jQuery('li[id^="item-"]').filter(function() { var number = this.id.replace(/\D+/, ''); return number >= 16 && number <= 19 }).addClass('the-class'); 

    jsFiddle 。

    (只是另一个答案)
    去自定义jQuery选择器。

    在你的情况下它’可能’是:

     $.expr[':'].customId = function(obj){ var $this = $(obj); var id = $this.attr('id'); var number = id.replace(/\D+/, ''); if ((new RegExp(/^item-/).test(id)) && (number > 15 && number < 20)) { return true; } return false; }; // Usage: $('a:customId').addClass('the-class'); 

    参考:
    http://jquery-howto.blogspot.com/2009/06/custom-jquery-selectors.html
    http://www.bennadel.com/blog/1457-How-To-Build-A-Custom-jQuery-Selector.htm