如何获取多个跨度的html内容并将值添加为类

时间:2014-03-19 01:58:07

标签: javascript jquery html

我的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');
    }

})

2 个答案:

答案 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)

DEMO

$('span').each(function() {
    var x = $(this).text();
    $(this).addClass('amenity-val-' + x);
});

这将迭代每个span标记,抓取它的文本并将其保存为var x,然后我们只需将该类添加到该范围。