将每个<p>中的文本作为div的子节点并存储在数组中

时间:2017-06-14 11:00:44

标签: javascript jquery

我正在尝试读取段标记内的内容,这是div的子节点,并将这些值存储到控制器并将其传递给控制器 这是代码:

 <div class = "proposal">
    <p> one </p>
    <p> two </p> 
    <p> three </p>
    <p> three </p> 
    <p> three </p>
    <p> three </p>
    </div> 
    Please help me to get the content of paragraph and store into an array using jquery.
I am trying to get a solution in this way:

var proposal = $("#Proposal").contents().filter(function() {
                                return this.nodeType === 3;
                            }) .wrap( "<p></p>" ).end();

我正在获取对象,但是,

for(i=0;i<proposal.length;i++){
    proposal = proposal[i].innerHTML
}

给我错误,  无法读取未定义的属性“长度”

2 个答案:

答案 0 :(得分:2)

&#13;
&#13;
var arr = $(".proposal p").map(function() {

  return $(this).text()

}).get();


console.log(arr)
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="proposal">
  <p> one </p>
  <p> two </p>
  <p> three </p>
  <p> three </p>
  <p> three </p>
  <p> three </p>
</div>
&#13;
&#13;
&#13;

  1. 使用.map()添加到数组中。
  2. 使用.text()与选择器$(".proposal p") - &gt;意思是所有具有类提议的元素的子元素

答案 1 :(得分:1)

这将获得每个p并将其推入数组。

PrintWriter