从div标签获取带有除法的textNode

时间:2016-05-26 07:52:24

标签: javascript jquery division textnode

<div class="list" data-id="1">One</div>
<div class="list" data-id="2">Two</div>
<div class="list" data-id="3">Three</div>
<div class="list" data-id="4">Four</div>
var text = $(".list").contents().filter(function() {
return this.nodeType == 3; }).text()
alert(text);

现在,我收到警报“OneTwoThreeFour”

但是,我希望得到“One | Two | Three | Four”这样......使用“|”分割

请帮助我.......

1 个答案:

答案 0 :(得分:3)

.join()

之后使用jQuery.map()
  

join()方法将数组的所有元素连接成一个字符串。   

   jQuery.map()将数组或对象中的所有项目转换为新的项目数组。

var text = $(".list").map(function() {
  return this.textContent;
}).get();

alert(text.join('|'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="list" data-id="1">One</div>
<div class="list" data-id="2">Two</div>
<div class="list" data-id="3">Three</div>
<div class="list" data-id="4">Four</div>

或使用您的方法

var text = $(".list").contents().filter(function() {
  return this.nodeType == 3;
}).get();
text = text.map(function(t) { //.map as text is a collection of `TextNode` objects
  return t.textContent;
});
alert(text.join('|'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="list" data-id="1">One</div>
<div class="list" data-id="2">Two</div>
<div class="list" data-id="3">Three</div>
<div class="list" data-id="4">Four</div>