【问题标题】:Replacing only text portion [duplicate]仅替换文本部分[重复]
【发布时间】:2016-03-29 20:58:19
【问题描述】:

我怎样才能只替换文本部分 Regret/Rlwl1 这里留下 input 元素原样:

<td id="td1" style="color: rgb(255, 0, 0);"><input type="RADIO" name="lccp_class4" value="3A">
Regret/Rlwl1</td>

【问题讨论】:

  • $('#td1').text("")
  • @Alex 它也会移除输入元素
  • 你确定会吗?
  • @user5858 检查我的解决方案。可能有更好的方法。
  • @PraveenKumar 确实

标签: jquery


【解决方案1】:

我自己的方式,但还有更好的方式。

$(function () {
  $("#test").contents().each(function () {
    if (this.textContent.trim().length > 0)
      $(this).replaceWith('Hello');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
  <input type="RADIO" name="lccp_class4" value="3A">
  Regret/Rlwl1
</div>

更新

对于那些因任何原因看不到输出的人,我得到这个:

更好的版本:

$(selector).contents().filter(function() {
  return this.nodeType == 3;
})
.replaceWith(something_else);

工作片段

$(function () {
  $("#test").contents().filter(function() {
    return this.nodeType == 3;
  })
  .replaceWith("Hello");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"><input type="RADIO" name="lccp_class4" value="3A">Regret/Rlwl1</div>

【讨论】:

  • OP 想从 td.... 中删除文本:P
  • @BhojendraNepal can I replace only: replace != remove.
  • 阅读How can I replace only the text portion Regret/Rlwl1 here leaving input element as it is:
  • @BhojendraNepal 这很奇怪。我得到了这个:i.imgur.com/MrQ9PDA.png
  • ^1 更新答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-27
  • 2012-10-21
  • 2015-12-16
  • 1970-01-01
  • 1970-01-01
  • 2015-08-10
  • 1970-01-01
相关资源
最近更新 更多