2014-03-26 69 views
0

我有2個div具有相同的類,但它們具有不同的值。 我想在jQuery循環中使用不同的值,但由於某種原因,腳本只使用第一個div的值。未能從同一類的2個div獲得不同的值

這裏是demo fiddle

HTML:

<div class="temp-stars"><p>5</p></div> 
<div class="temp-stars"><p>2</p></div> 

CSS:

.temp-stars { position: relative; background: #666; padding: 10px; width: 100px; height: 10px; } 
.temp-stars p {display: none;} 
.stars {position: relative; width: 100%; height: 100%; } 
.single-star-yellow { width: 10px; height: 10px; background: #f90; float: left; margin-right:5px; } 

的jQuery:

$(function() { 
    var num = parseInt($(".temp-stars p").html()); 
    alert(num) 
    $(".temp-stars").append("<div class='stars'></div>") 
    for (var i = 0; i < num; i++) { 
     $(".stars").append("<div class='single-star-yellow'></div>") 

    }; 
}); 

回答

2

您需要使用

$(".temp-stars").each(function() { 
    var num = parseInt($(this).find("p").html()); 

    var $star = $("<div class='stars'></div>").appendTo(this) 
    for (var i = 0; i < num; i++) { 
     $star.append("<div class='single-star-yellow'></div>") 
    }; 
}); 

演示:Fiddle

已使用的.html()吸氣版本,以獲得num值,它會始終在給定元素集合返回第一個元素的值。

你需要使用像上面那樣的循環來解決它。


多一點書呆子

$(".temp-stars").each(function() { 
    var num = +$(this).find("p").html(); 

    $("<div class='stars'></div>").append(new Array(num + 1).join("<div class='single-star-yellow'></div>")).appendTo(this) 
}) 

演示:Fiddle

+0

謝謝。這工作非常好。我確實嘗試過使用每個函數,但是查看你的代碼我知道我有很多東西在我的嘗試中失蹤。 –

相關問題