<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(function() {
var players = [{ name: "Paul", rank: 1}, {name: "Michael", rank: 2}];
$.each(players, function(key, value){
$("#containerofPlayers").append('<div id="' + value.name + '">' + value.name + ' is ranked ' + value.rank + '</div>');
});
});
</script>
發生了什麼事是你有一個數組對象的。循環訪問數組中的每個對象以獲取其數據。然後創建並附加一個新的div,其值爲<div id="containerofPlayers"></div>
元素。
希望這會有所幫助。
編輯:如果你不想創建jQuery中的<div>
元素,但只要將文字,你可以這樣做,而不是:
$('#'+value.name).text(value.name + " is ranked " + value.rank);
編輯答案:
既然你已經改變了您的原始問題,
<div><input name="name" /></div> <div><input name = "rating" /></div>
做些更像↓
<div id="players">
<div class="player">
<label>Name: </label><input class="playerName" type="text"/>
<label>Rank: </label><input class="playerRank" type="number"/>
</div>
<div class="player">
<label>Name: </label><input class="playerName" type="text"/>
<label>Rank: </label><input class="playerRank" type="number"/>
</div>
</div>
然後在jQuery的
$(function() {
var players = []; //create an Array
$("#players .player").each(function(i, obj){
var playerName = $(this).children('.playerName').val();
var playerRank = $(this).children('.playerRank').val();
$(this).push({"name": playerName, "rank": playerRank}); // this will give you an array of objects like in my previous answer, then you can use that data to display it.
});
players.sort(function(a, b) {
return (a.rank - b.rank) || a.name.localeCompare(b.name);
});
$.each(players, function(index, value){
$("#result").append('<div id="' + value.name + '">' + value.name + ' is ranked ' + value.rank + '</div>');
})
});
注意,額定輸入字段簡化了操作。沒有更多的代碼查找巫術。簡單的方法是更清潔,更好,恕我直言。 – verlager
我改變了列表的格式。明智的直接代碼是我的目標。我在兩個相關的輸入字段中添加了name =「name」和name =「rating」。希望有人能幫助我。 – verlager
我越來越深入。我將重新編輯該問題。 – verlager