【问题标题】:How can I replace the text of an HTML tag如何替换 HTML 标记的文本
【发布时间】:2012-05-03 07:46:22
【问题描述】:

我不知道怎么称呼它,但让我称之为半内部文本。

例子

<div id='myDiv'>
    This is the semi-inner text
    <div id='other'></div>
    This is the semi-inner text
<div>

我想使用 jquery 删除/替换那些 This is the semi-inner text

我该怎么做?

【问题讨论】:

  • 将其包裹在&lt;span class="semiTxt"&gt;&lt;/span&gt;中并使用JS替换其中的文本
  • 你应该用 span、div、p 或其他东西来包装它。如果某些文本未包装,则它不是有效的 html 页面。

标签: jquery html text tags innerhtml


【解决方案1】:

如果你只关心子节点...

$('#myDiv').contents().filter(function() {
    return this.nodeType == 3
}).each(function() {
    this.data = this.data.replace(/This is the semi-inner text/g, 'swapped');
});​

jsFiddle.

如果要检查所有后代节点,请在检测到元素节点时使函数递归 (this.nodeType == 1)。

【讨论】:

    【解决方案2】:
    $('#myDiv')
        .contents()
        .filter(function() {
            return this.nodeType == 3;
        })
        .each(function() {
            $(this).remove();
        });
    

    【讨论】:

      【解决方案3】:

      使用 contents() 过滤掉所有等于 3 的 nodeType 并删除:

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

      【讨论】:

        【解决方案4】:

        使用以下代码替换内容

        $("#other").html("your code");
        

        并且用户将您的代码包装在带有 id 的 span 标记中

        【讨论】:

          【解决方案5】:

          最简单的方法是将其放置在具有如下 id 的 span 中:

          <div id='myDiv'>
              <span id="myInnerText">This is the semi-inner text</span>
              <div id='other'></div>
              This is the semi-inner text
          <div>
          

          然后像这样替换它:

          $("#myInnerText").text("replacement text");
          

          【讨论】:

            【解决方案6】:

            你也可以这样做:

            target_div = $("#myDiv")
              reg_exp  = /This is the semi-inner text/g;
              new_text = "some other text"
            
              target_div.html(
                target_div.html()
                  .replace(
                    new RegExp(reg_exp),
                    new_text)
                    );
             });
            

            Demo

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2012-03-13
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2014-07-30
              • 1970-01-01
              • 2011-04-17
              相关资源
              最近更新 更多