gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:34:06 32 4
gpt4 key购买 nike

<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”

但是,我想像这样得到“一|二|三|四”......使用“|”部门

请帮助我......

最佳答案

使用.join()之后jQuery.map()

The join() method joins all elements of an array into a string.

jQuery.map() translate all items in an array or object to new array of items.

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>

关于javascript - 从 div 标签中获取带有除法的 textNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37454751/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com