我如何提取div的文本部分而忽略内部html标签的文本
这是div
<div class="MessageBox">I want to see only this message<span....>Click Here to collapse</span></div>
这是javascript函数中的jquery
var message= $(".MessageBox").text();
现在我收到消息=“我只想看到这条消息点击这里折叠”
我想要消息 =“我只想看到这条消息”
您可以使用该clone()方法克隆主元素,然后删除该克隆的子元素以丢弃您不想要的部分:
var clone = $('.MessageBox').clone();
clone.children().remove();
var message = clone.text();
当然,您可以跳过克隆部分。但是你实际上会从页面中删除元素,我不确定你是否想要这样做。克隆主要元素允许您操作它的副本,而不是用户实际看到的副本。
您可以过滤仅文本(排除元素)的节点类型的选择器,并像这样获取文本:
var text = $('.MessageBox').contents().filter(function() {
return this.nodeType == 3;
}).text();
尝试:
$('.MessageBox')
.clone() //clones the element
.children() //selects all the children
.remove() //removes all the children
.end() //again goes back to selected element
.text(); //gets the text of element
当然,你可以这样做:
div = $('.MessageBox').clone();
inner = div.children();
inner.remove();
alert(div.text());