如何从#data中删除包含子跨度的跨度,以便#result包含“仅剩下文本”?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="data">Only text left <span class='price'>remove this<span> €0,00</span> </span>
</div>
<div id="result"></div>
<script type="text/javascript">
$(document).ready(function() {
var nhtml = $('#data').html();
$('#result').html(nhtml);
});
</script>
答案 0 :(得分:2)
使用 contents()
和 filter()
从中过滤文本节点,然后通过 text()
获取文字内容强>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="data">Only text left <span class='price'>remove this<span> €0,00</span> </span>
</div>
<div id="result"></div>
<script type="text/javascript">
$(document).ready(function() {
var nhtml = $('#data')
.contents() // get all child nodes including text and comment node
.filter(function() {
return this.nodeType == 3; // filter text node from it
}).text(); // get the text content from it
$('#result').html(nhtml);
});
</script>
&#13;
使用 clone()
克隆元素并删除范围,然后获取html内容
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="data">Only text left <span class='price'>remove this<span> €0,00</span> </span>
</div>
<div id="result"></div>
<script type="text/javascript">
$(document).ready(function() {
var nhtml = $('#data')
.clone() // clone the element
.find('.price') // get the span
.remove() // remove the span
.end() // back to cloned element
.html(); // get the html content from cloned element
$('#result').html(nhtml);
});
</script>
&#13;
答案 1 :(得分:0)
我使用.remove()函数删除它,你可以参考下面的小提琴链接
$( document ).ready(function() {
$(".price").remove();
var nhtml = $('#data').html();
$('#result').html(nhtml);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="data">Only text left <span class='price'>remove this<span> €0,00</span> </span> </div>
<div id="result"> </div>