[英]How can I push elements into an array that's within an object? (javascript/jQuery)
如何將存儲在列表中的數據推入嵌套在對象中的特定數組(“項目:[]”)中?
var obj = {
name: customerName,
items: [],
price: [] }
<ul>
<li>Blah blah blah<li>
</ul>
obj.items.push(1);
obj.price.push(2);
將導致:
{
name: 'someName',
items: [ 1 ],
price: [ 2 ]
}
要將數據從列表項推送到items
數組中,可以執行以下操作:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>jQuery list</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
<script>
$(document).ready(function () {
var obj = {
items: []
};
$('li').each(function () {
// Extract the text node from the list item.
var textNode = $(this).text();
obj.items.push(textNode);
});
console.log(obj.items); // [ "one", "two", "three" ]
});
</script>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.