我的HTML:
<div class="inside">
<ul class="fourcol first">
<li class="amenity-item">Something: <span>0</span></li>
<li class="amenity-item">Something: <span>0</span></li>
<li class="amenity-item">Something: <span>1</span></li>
<li class="amenity-item">Something: <span>0</span></li>
<li class="amenity-item">Something: <span>1</span></li>
<li class="amenity-item">Something: <span>0</span></li>
<li class="amenity-item">Something: <span>1</span></li>
<li class="amenity-item">Something: <span>1</span></li>
<li class="amenity-item">Something: <span>0</span></li>
</ul>
</div>
我想要完成的任务:
<div class="inside">
<ul class="fourcol first">
<li class="amenity-item">Something: <span class="amenity-val-0">0</span></li>
<li class="amenity-item">Something: <span class="amenity-val-0">0</span></li>
<li class="amenity-item">Something: <span class="amenity-val-1">1</span></li>
<li class="amenity-item">Something: <span class="amenity-val-0">0</span></li>
<li class="amenity-item">Something: <span class="amenity-val-1">1</span></li>
<li class="amenity-item">Something: <span class="amenity-val-0">0</span></li>
<li class="amenity-item">Something: <span class="amenity-val-1">1</span></li>
<li class="amenity-item">Something: <span class="amenity-val-1">1</span></li>
<li class="amenity-item">Something: <span class="amenity-val-0">0</span></li>
</ul>
</div>
我的尝试:
$(function() {
var value_of_span = $.each('span.amenity-val').html()
if (value_of_span == 0) {
$('span.amenity-val').addClass('amenity-val-0');
}
if (value_of_span == 1) {
$('span.amenity-val').addClass('amenity-val-1');
}
})
答案 0 :(得分:3)
您可以使用:
1)$.each()
遍历span
内的所有.amenity-item
元素:
2)text()
获取文字内的文字
3)addClass()
分别根据检索到的文本添加类
$.each($('.amenity-item span'), function () {
var text = $(this).text();
$(this).addClass('amenity-val-' + text);
});
<强> Fiddle Demo 强>
答案 1 :(得分:2)
$('span').each(function() {
var x = $(this).text();
$(this).addClass('amenity-val-' + x);
});
这将迭代每个span标记,抓取它的文本并将其保存为var x,然后我们只需将该类添加到该范围。