只删除普通文本,而不删除span元素。

4

我想清除“普通文本”,但不包括glyphicon的内容。

重要的代码部分及其结果:

  1. $("#btn_test").html()将给我:

    "<span class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></span> Speichern &amp; schließen"

  2. $("#btn_test").text()将给我:

    " Speichern & schließen"

我只想删除文本“ Speichern & schließen”,而不使用.replace(...)函数(因为文本是动态的)。

我尝试了$("#btn_test").text(""),但这也会清除我的元素。

谢谢。

更新('possible duplicate'): 是的,这与此处相同的问题,但不是Chris Davis的答案,那个解决了我的问题。


需要删除的文本可能在我的 span 元素之前或之后。 - 99999
1
既然你已经有了一个被接受的答案,你仍然可以将其关闭为重复。未来的答案可能非常相似,没有必要保持开放状态(这不会阻止投票也不会删除你的问题)。 - Kaiido
2个回答

5

移除文本节点,例如:

$('#btn_test').contents().filter(function(){
  return this.nodeType === 3;
}).remove();

或者更简单地说,如果它总是最后一个:
$('#btn_test').contents().last().remove();

-jsFiddle-


2

Simplest way would be to wrap your text in a span — it then becomes trivial to remove this text.

$(document).ready(function() {
 $('#btn_test .text').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn_test">
  <span class="glyphicon glyphicon-floppy-disk"
        aria-hidden="true"></span> 
  <span class="text">Speichern &amp; schließen</span>
</button>

jsFiddle link


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接