开发者

How to select an object if it contains a number with jquery?

I have a couple divs like so:

<div>1</div>
<div>2</div

all the way through to

<div>11</div>
<div>12</div>

And so on.

What I'm wanting is a jquery select that picks one of these, like so:

$('.ticketNumber:contains("1")').addClass('something');

The problem with this of course, is its going to select any of the divs that contain the number 1 and not just the one that only contains 1.

开发者_如何学JAVA

So how does one go about telling jquery to do an exact select rather than a wildcard type?


you can extend the selector

$.extend($.expr[':'],{
  containsNumber: function(a,i,m) {

    var text = $(a).text();

    return parseInt(text) == parseInt(m[3]);
  }
});

then you can use your extended selector

$('.ticketNumber:containsNumber(1)').addClass('something');


While filter is an easy option, you could do a little preprocessed to select more quickly.
This code created an array of tickets, for easy access. This is good if they don't change often, and have small numbers (otherwise the array would be too big, but you can easily switch to an associative array):

var tickets = [];

$(function(){
  $('div').each(function(){
    var div = $(this);
    var n = parseInt(div.text(), 10);
    tickets[n] = div;
  }); //div.each

  tickets[12].css('color', 'red');
}); //doc.ready

The next option is less popular, but works well. jQuery does similar things internally, by the way. Here, we use attr to add a custom attribute and select by it (if it bothers you, you can add a class like ticket12, or use a standard attribute). This is easier to maintain than an array if you make a lot of changes to your page:

$(function(){ 
  $('div').each(function(){ 
    var div = $(this); 
    var n = div.text(); 
    div.attr('ticket', n); 
  }); //div.each 

  $('[ticket=3]').css('color', 'blue'); 
}); //doc.ready 

See both examples in action here: http://jsbin.com/etapu3

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜