在下面的示例中,我需要选择每个div中的数字以相应地显示颜色编码的消息。
<div class="result_a">
<label> A number </label>
4
</div>
<div class="result_b">
<label> B number </label>
0
</div>
<div class="result_c">
<label> C number </label>
1
</div>
只有当每个div中只有数字时,使用下面的代码才有效。在选择数字之前,必须有一种方法首先除去每个div中的数字以外的所有数字,但我还没有找到这样的方法。
$(" [class^='result_'] ").each(function() {
var count = $(this).text();
var dh = $(this),
dhn = dh.attr("class").match(/result_(.*)/)[1];
var aa = '0';
var msg = '0';
if (count < 1) {
var aa = ('green');
var msg = (' Your ' + dhn + ' is very good');
} else if (count >= 1 && count < 3) {
var aa = ('blue');
var msg = (' Your ' + dhn + ' is bad');
} else if (count >= 3) {
var aa = ('red');
var msg = (' Your ' + dhn + ' is very bad');
} else {
var aa = ('');
}
$(this).removeClass('red green blue').addClass(aa).text(count + msg);
});
我也许可以使用所用的方法
here
(复制到下面)但不确定如何使用这个来满足我提到的需要(只需选择每个div中的数字并将上面的jQuery应用到)。
function autospan() {
var exp = /-?[\d.]+/g;
$('*:not(script, style, textarea)').contents().each(function() {
if (this.nodeType == Node.TEXT_NODE) {
var textNode = $(this);
var span = $('<span/>').text(this.nodeValue);
span.html(span.html().replace(exp, '<span class="foo">$&</span>'));
textNode.replaceWith(span);
}
});
}
$(autospan);