Jquery基于数值内容更改对象的CSS类 [英] Jquery Changing CSS class of object based on numeric content
问题描述
即将动态输出百分比0-100%
Going to be outputting percentages dynamically 0-100%
希望根据百分比添加CSS类。红色为0%,蓝色为100%。
Want to add CSS class based on percentage. Red for 0% and Blue for 100% progressively.
标记将是
<span class="blue">100%</span>
原来我一直在想这行....
Originally I had thought something along this line....
$("span:contains('100%')").css("color", "#0000ff");
但是只包含搜索第一个整数并为1,2,3,4,5应用不同的类, 6,7,8,9
只有这个方法的问题是单个数字的数字将被视为相同的双。 IE 7%和70%会有相同的类,并且不正确。
But contains only searching first integer and applying different classes for 1,2,3,4,5,6,7,8,9 only problem with this method is single digit numbers would be treated the same as double. IE 7% and 70% would have the same class and wouldn't be correct.
这些不是特定的金额,他们将动态地改变。
These aren't specific amounts, they are going to dynamically change all the time. I am not very good at writing my own jquery so any help is appreciated.
推荐答案
DEMO: http://jsfiddle.net/JAAulde/GJh3j/
如果页面上有很多元素,包含将是一个非常昂贵的查询。
我会:
Contains is going to be a pretty expensive query if you have a lot of elements on the page. I would:
向所有元素添加类:
<span class="percent-holder">100%</span>
<span class="percent-holder">100%</span>
<span class="percent-holder">0%</span>
<span class="percent-holder">100%</span>
找到所有这些元素,分析他们的文字,做你想要的:
Find all those elements, analyze their text, do what you want:
$( '.percent-holder' ).each( function()
{
var $this = $( this ),
classToAdd = null;
switch( $this.text() )
{
case '100%':
classToAdd = 'blue';
break;
case '0%':
classToAdd = 'red';
break;
}
if( classToAdd !== null )
{
$this.addClass( classToAdd );
}
} );
这篇关于Jquery基于数值内容更改对象的CSS类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!