创建简单的js对象并将它们存储到js数组中

时间:2015-03-28 17:14:53

标签: javascript jquery

在html dom里面我有以下结构

<div id="myTitles">
<ul>
  <li>
      Title:<title>A</title><br>
      Second title: <secTitle>B</secTitle><br>
      Third title: <thirdTitle>3</thirdTitle>
  </li>
  <hr>
  <li>
      Title:<title>B</title><br>
      Second title: <secTitle>C</secTitle><br>
      Third title: <thirdTitle>9</thirdTitle>
  </li>   
</ul>
</div>

运行时未知myTitles div的ul内的列表元素数。所以我要var nrOfTitles = $('#myTitles ul li').length;来确定有多少。

现在,我想创建一些简单的javascript对象,它将保存这些值(存储在此语义标记(titlesecTitlethirdTitle)中)并将它们存储在js数组中

2 个答案:

答案 0 :(得分:1)

var items = $("#myTitles > ul > li");

var arr = [];

items.each(function(){
    arr.push([$(this).find("title").text(),$(this).find("secTitle").text(),$(this).find("thirdTitle").text()])
})

使用<li>的当前组合,它将包含:

[["A","B","3"],["B","C","9"]]

或者您可以将属性存储为对象:

var items = $("#myTitles > ul > li");

var arr = [];

items.each(function(){
    arr.push({title:$(this).find("title").text(),secTitle:$(this).find("secTitle").text(),thirdTitle:$(this).find("thirdTitle").text()})
})

然后你会得到

[{title:"A",secTitle:"B",thirdTitle:"3"},{title:"B",secTitle:"C",thirdTitle:"9"}]

答案 1 :(得分:0)

您可以使用$.fn.map方法方便地创建对象数组:

var obj = $('#myTitles ul li').map(function() {
    return {
        title: $(this).find('title').text(),
        secTitle: $(this).find('secTitle').text(),
        thirdTitle: $(this).find('thirdTitle').text()
    };
}).get();

alert(JSON.stringify(obj, null, 4));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myTitles">
<ul>
  <li>
      Title:<title>A</title><br>
      Second title: <secTitle>B</secTitle><br>
      Third title: <thirdTitle>3</thirdTitle>
  </li>
  <hr>
  <li>
      Title:<title>B</title><br>
      Second title: <secTitle>C</secTitle><br>
      Third title: <thirdTitle>9</thirdTitle>
  </li>   
</ul>
</div>

但是,由于您在HTML中使用自定义标记,请记住为IE8创建它们,如果您计划支持此浏览器,例如document.createElement('title');