Javascript 创建包含多个HTML元素属性的嵌套数组
如果我有这样的HTML:Javascript 创建包含多个HTML元素属性的嵌套数组,javascript,json,Javascript,Json,如果我有这样的HTML: <ul> <li id="id1">Some Text</li> <li id="id2">Other Text</li> <-- more items could be here --> </ul> 其中id和name等于$(this).attr('id')和$(this).text()其中$(this)指单个li项 itemsData = []; $('ul
<ul>
<li id="id1">Some Text</li>
<li id="id2">Other Text</li>
<-- more items could be here -->
</ul>
其中id
和name
等于$(this).attr('id')
和$(this).text()
其中$(this)
指单个li
项
itemsData = [];
$('ul > li').each(function(){
itemsData.push({"id" : this.id, "name" : $(this).text()})
});
(请参见控制台上的输出)使用
。每个:
var itemsData = [];
$('li').each(function() {
var $this = $(this);
itemsData.push({
id: $this.attr('id'),
name: $this.text()
});
});
console.log(itemsData);
是的,我在等待答案的时候用同样的方法解决了这个问题。这很容易,我想我只是累了。我仍然会把你的答案记为正确。:)@我明白了,你有点不耐烦吧?;-)
var itemsData = [];
$('li').each(function() {
var $this = $(this);
itemsData.push({
id: $this.attr('id'),
name: $this.text()
});
});
console.log(itemsData);
var arr = new Array();
$("ul li").each(function(index){
arr[index]['id'] = $(this).attr('id');
arr[index]['name'] = $(this).attr('name');
});