【问题标题】:Replace only text inside a div using jquery使用 jquery 仅替换 div 内的文本
【发布时间】:2021-06-22 01:13:26
【问题描述】:

我有一个像这样的 div:

<div id="one">
       <div class="first"></div>
       "Hi I am text"
       <div class="second"></div>
       <div class="third"></div>
</div>

我正在尝试使用 jquery 仅将文本从“Hi I am text”更改为“Hi I am replace”。 这可能很容易,但我做不到。

使用$('#one').text('') 只会清空整个#One div。

【问题讨论】:

  • 创建fiddle 可能会有所帮助
  • 使用 $('#one').find('.first').text('Hi I am replace');而不是 $('#one').text();或者您可以使用 $('.first').text('Hi I am replace'); 直接访问元素并替换文本;

标签: javascript jquery


【解决方案1】:

文本不应单独存在。将其放入span 元素中。

改成这样:

<div id="one">
       <div class="first"></div>
       <span>"Hi I am text"</span>
       <div class="second"></div>
       <div class="third"></div>
</div>
$('#one span').text('Hi I am replace');

【讨论】:

  • 这并没有回答 OP 的问题,他们没有说他们可以控制 HTML。
  • 这是可行的,但如何确定执行与否?如果空白或标签更改,我可以运行异常吗?绑定不成功,因为这个 div 是由 code.from REST 或数据库创建的
  • 这是错误的。 .text 会将文本尾随现有文本。
【解决方案2】:

找到文本节点(nodeType==3)并替换textContent

$('#one').contents().filter(function() {
    return this.nodeType == 3
}).each(function(){
    this.textContent = this.textContent.replace('Hi I am text','Hi I am replace');
});

请注意,根据docs,您可以将上面硬编码的3 替换为Node.TEXT_NODE,这样会更清楚您在做什么。

$('#one').contents().filter(function() {
    return this.nodeType == Node.TEXT_NODE;
}).each(function(){
    this.textContent = this.textContent.replace('Hi I am text','Hi I am replace');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="one">
       <div class="first"></div>
       "Hi I am text"
       <div class="second"></div>
       <div class="third"></div>
</div>

【讨论】:

  • 这应该是公认的答案,因为这不需要您更改 html!
  • @Jamiec FWIW 我喜欢这个答案,因为它允许替换而不用担心标记/脚本等。
  • 这对我来说非常有效。有时我们在不允许更改 HTML(即 SharePoint)的情况下工作。谢谢
  • 为什么不将3 替换为Node.TEXT_NODE 以使sn-p 更清晰?
  • @Paul 谢谢,它更清楚了,所以我把它作为这个旧答案的注释。
【解决方案3】:

您需要将文本设置为非空字符串。此外,.html() 函数应该在保留 div 的 HTML 结构的同时做到这一点。

$('#one').html($('#one').html().replace('text','replace'));

【讨论】:

  • 虽然这在这种情况下可行,但我不喜欢这个选项,因为如果你用“第二”这个词替换“第一”这个词,或者只是用“我”替换它会搞砸你的标签
【解决方案4】:

如果您确实知道要替换的文本,则可以使用

$('#one').contents(':contains("Hi I am text")')[0].nodeValue = '"Hi I am replace"';

http://jsfiddle.net/5rWwh/

或者

$('#one').contents(':not(*)')[1].nodeValue = '"Hi I am replace"';

$('#one').contents(':not(*)')在这种情况下选择非元素子节点文本节点,第二个节点是我们要替换的节点。

http://jsfiddle.net/5rWwh/1/

【讨论】:

  • From jQuery 1.8.3 $('#one').contents(':not(*)') 将不选择任何内容。
【解决方案5】:

另一种方法是保留该元素,更改文本,然后附加该元素

const star_icon = $(li).find('.stars svg')
$(li).find('.stars').text(repo.stargazers_count).append(star_icon)

【讨论】:

    【解决方案6】:

    以防万一您无法更改 HTML。非常原始但简短且有效。 (它将清空父 div,因此子 div 将被删除)

    $('#one').text('Hi I am replace');
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div id="one">
      <div class="first"></div>
      "Hi I am text"
      <div class="second"></div>
      <div class="third"></div>
    </div>

    【讨论】:

    • 这会删除#one的所有子div
    • @ScotNery 谢谢你,我已经更新了答案。 (尽管它在技术上回答了这个特定问题)我假设除了用具有 id 的标签包装文本之外,这将非常具有挑战性。唯一的另一件事就是匹配一个要替换的字符串,但它真的很脆弱。
    【解决方案7】:

    我遇到了同样的问题,但 文本是父元素内的第一个节点。在这种情况下,您可以执行以下操作,而且速度非常快:

    // find the children elements
     termsChildren = $('#one').children()
    
    // replace the text, then re-append the children element.
     $('#one').text(' "Hi I am replace" ').append(termsChildren)
    

    否则,您必须指定哪些孩子必须在文本之前,哪些在之后:

    
    // find the children elements
     termsChildren = $('#one').children()
    
    // remove all the content
     $('#one').text(' ')
    // append the first child element
     $('#one').append(termsChildren[0])
    // add the new text and then the other children
     $('#one').text(' "Hi I am replace" ').append(termsChildren.slice(1))
    
    

    【讨论】:

      【解决方案8】:

      当您用 jQuery 替换元素的纯文本时,您不能单独放置纯文本,否则它将清除和/或替换整个元素。您应该将所有纯文本放在 &lt;span&gt; 元素中:

      $(document).ready(function() {
        $("#change-btn").click(function() {
          $("#one").children("span").text("Hi I am replace");
        });
      });
      <!-- Import CSS -->
      <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
      <!-- Import JavaScript -->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
      
      <div class="m-2">
        <div id="one">
          <div class="first"></div>
          <span>Hi I am text</span>
          <div class="second"></div>
          <div class="third"></div>
        </div>
        <button type="button" class="btn btn-primary btn-sm mt-2" id="change-btn">Click to change text</button>
      </div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-29
        • 1970-01-01
        相关资源
        最近更新 更多