最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Extending attributes selector with Less Than & Greater Than in jQuery - Stack Overflow

programmeradmin3浏览0评论

What would be the correct way to extend the jQuery attributes selector so that it supports Less Than and Greater Than?

I have some elements which contain a custom attribute SequenceNumber holding an integer. (Before anyone starts I cant use the data property (I think?) because this html is determined at runtime and generated serverside)

Either way. What I am looking to achieve is the ability to select a number of elements that contain a SequenceNumber BETWEEN X AND Y.

So basically something like this

$("#divSequenceGrid ul[SequenceNumber=>'1'][SequenceNumber<='10']").each(func);

Obviously I can do this by going

$("#divSequenceGrid ul").each(function (index, value) {
    //Push into an array those that fit my criteria 
});

But I'm wondering if there is a butter way?

What would be the correct way to extend the jQuery attributes selector so that it supports Less Than and Greater Than?

I have some elements which contain a custom attribute SequenceNumber holding an integer. (Before anyone starts I cant use the data property (I think?) because this html is determined at runtime and generated serverside)

Either way. What I am looking to achieve is the ability to select a number of elements that contain a SequenceNumber BETWEEN X AND Y.

So basically something like this

$("#divSequenceGrid ul[SequenceNumber=>'1'][SequenceNumber<='10']").each(func);

Obviously I can do this by going

$("#divSequenceGrid ul").each(function (index, value) {
    //Push into an array those that fit my criteria 
});

But I'm wondering if there is a butter way?

Share Improve this question edited Feb 1, 2015 at 16:35 Deduplicator 45.7k7 gold badges72 silver badges123 bronze badges asked Oct 5, 2011 at 5:50 Maxim GershkovichMaxim Gershkovich 47.2k46 gold badges162 silver badges247 bronze badges 1
  • Could filter possibly serve your needs? api.jquery./filter – Deets McGeets Commented Oct 5, 2011 at 5:54
Add a ment  | 

2 Answers 2

Reset to default 11

Using .filter()

  $("#divSequenceGrid ul").filter(function(){
        return  $(this).attr("sequenceNumber") >=1 && $(this).attr("sequenceNumber") <=10}).css("color", "red");

Here's a demo: http://jsfiddle/jFt9N/3/

You can use jQuery Selector expressions like this

$.extend($.expr[':'], {
  sMore: function(e, i, m) { return parseInt($(e).attr('SequenceNumber')) >= m[3]; },
  sLess: function(e, i, m) { return parseInt($(e).attr('SequenceNumber')) <= m[3]; }
});

$(function () {
  alert($('div:sMore(2):sLess(4)').length);
});
发布评论

评论列表(0)

  1. 暂无评论