2014-03-19 69 views
0

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

}) 

回答

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

2

DEMO

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

這將遍歷每個跨度標籤,抓住它的文本,並將其保存爲變種x,然後我們只是簡單地類添加到該跨度。