我的HTML页面中有这个div:
<div id="" class="ellipsize-text">
<h4>Sherlock</h4>
<span>S2:E2</span>
<span>The Hounds of Baskerville</span>
</div>
我想获得完整的标题,最后得出如下结论:
Sherlock S2:E2“巴斯克维尔猎犬”
我对此的第一个尝试是调用$(".video-title").first()[0].innerText
,它生成SherlockS2 2:E2Baskerville猎犬。注意这些段是如何在没有空格的情况下挤在一起的。然后我试着遍历孩子和解析片段,但我肯定做错了什么,似乎不能正确地遍历它。
获取内部html (使用jQuery)以产生我想要的结果的最有效方法(或者至少是最简单的方法)是什么?
发布于 2017-10-08 06:12:13
您可以使用text()
方法获取文本内容。或者,如果需要空间分隔子元素的文本内容,则在子节点上迭代并生成内容。
console.log(
$('.ellipsize-text').text().trim()
)
// or with space
console.log(
$('.ellipsize-text')
// get all child nodes
.contents()
// iterate over the child nodes
.map(function() {
// return the text content of the element
return $(this).text().trim();
})
// get the result as an array from the jQuery object
.get()
// join the array strings with a single space
.join(' ')
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="" class="ellipsize-text">
<h4>Sherlock</h4>
<span>S2:E2</span>
<span>The Hounds of Baskerville</span>
</div>
发布于 2017-10-08 06:11:50
要使用给定的类( div
中的ellipsize-text
)对每个类执行此操作,请执行以下操作:
$(".ellipsize-text").each(function() {
console.log($(this).children().map(function() {
return $(this).text();
}).get().join(" "));
});
我们使用children
获取div
的所有子节点,然后使用map
获取他们的文本,使用get
获取数组(而不是jQuery对象),使用join(" ")
将它们与空格相加。
现场复印:
$(".ellipsize-text").each(function() {
console.log($(this).children().map(function() {
return $(this).text();
}).get().join(" "));
});
<div id="" class="ellipsize-text">
<h4>Sherlock</h4>
<span>S2:E2</span>
<span>The Hounds of Baskerville</span>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
https://stackoverflow.com/questions/46631979
复制