jQuery ID编号范围

jQuery ID Number Range

本文关键字:范围 编号 ID jQuery      更新时间:2023-09-26

我正在尝试编写一个jQuery脚本,该脚本将添加一个类来列出某个ID范围内的项。我在身份证中使用数字,并想调整身份证的范围。

<li id="item-15">Something</li>
<li id="item-16">Something</li>
<li id="item-17">Something</li>
<li id="item-18">Something</li>
<li id="item-19">Something</li>

我想增加一个类,说第16项到第19项。我该怎么做?

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

我真的不知道该怎么做。也许是.each()

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.slice()方法是为设计的。

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

所以

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/

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