best jquery way to find and filter and apply css classes
ok say we have
<span class="foo">7</span>
<span class="foo">2</span>
<span class="foo">9</span>
and want to apply a css class of 'highest' to 'span.foo'.text > 7 and css class of medium to values > 4 and <= 7 and css class of开发者_如何学Python lowest to <= 4
example of desired result:
<span class="foo medium">7</span>
<span class="foo lowest">2</span>
<span class="foo highest">9</span>
Is this a find and filter situation? I'm sure it's common, but I can't seem to find the best way to write it. Thanks
$("span.foo").each(function(){
var num = parseInt(this.innerHTML, 10);
if (num > 7)
this.className += " highest";
else if (num <= 4)
this.className += " lowest";
else
this.className += " medium";
});
You could do it with find/filter. It would be easier to do it with each
:
$('span.foo').each(function(){
var $this = $(this),
val = parseInt($this.html(),10);
if (val > 7) {
$this.addClass('highest');
} else if (val <= 4) {
$this.addClass('lowest');
} else {
$this.addClass('medium');
}
});
$(".foo").each(function()
{
var layer=$(this);
var val=parseInt(layer.text());
if(val>7)layer.addClass("highest")
else
if(val>4 && val<=7)layer.addClass("medium");
else {
layer.addClass("lowest");
}
});
Here you have it: http://jsfiddle.net/dactivo/n6GvJ/
If you prefer with filter even if it is less efficient:
$('.foo').filter(function(index) {
return parseInt($(this).text())>7
}).addClass("highest");
$('.foo').filter(function(index) {
return (parseInt($(this).text())>4 && parseInt($(this).text())<=7)
}).addClass("medium");
$('.foo').filter(function(index) {
return parseInt($(this).text())<=4
}).addClass("lowest");
Like here: http://jsfiddle.net/dactivo/5tGsj/
精彩评论