[英]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 lowest to <= 4 并且想要将'highest'的css类应用于'span.foo'。text> 7和css类的medium到值> 4和<= 7以及css类的最低到<= 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. 你可以用find / filter做到这一点。 It would be easier to do it with each
: 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/ 在这里你有: 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/ 喜欢这里: http : //jsfiddle.net/dactivo/5tGsj/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.