我試圖獲取HTML列表的文本值,然後將它們推送到JSON對象中的單個鍵值。我希望JSON內容看起來像{"players": ["James","Emma","Vincent"]}
。我目前的嘗試如下。如何將HTML列表值作爲javascript中的數組推送到單個JSON密鑰
// create array with empty player key
var infoArray = [{
"players": ""
}];
// set the player key to a var
var mykey = 'players';
// for each player
$(".player").each(function() {
infoArray[mykey].push({
// add the player's name to the key
$(this).text();
});
});
//show the resulting json
$("#list").html(JSON.stringify(infoArray));
pre {
word-wrap:break-word;
padding:10px;
margin:10px;
background:#eee;
line-height: 1.7
}
<ul>
<li class="player">James</li>
<li class="player">Emma</li>
<li class="player">Vincent</li>
</ul>
<h3>JSON result</h3>
<pre id="list"></pre>