【问题标题】:Using .replace to replace text with HTML?使用 .replace 将文本替换为 HTML?
【发布时间】:2016-10-17 09:28:07
【问题描述】:

我想使用 jQuery 将文本替换为图像。我一直在使用 .replace 函数用更多文本替换文本。如何将文本替换为 html 标记,例如 标记。

这是我的代码:

function wow() {
  $('.messageBody').each(function() {
      var text = $(this).text();
      var image = '<img class = "emote" src = "trump.png">'
      $(this).text(text.replace(':trump:', image.outterHTML));
  });
}
setInterval(wow, 1000);

这是 HTML:

<span class="messageBody">:trump:</span>

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    如果您使用.html 而不是.text,它将起作用。更改此行:

      $(this).text(text.replace(':trump:', image.outterHTML));
    

    对此:

      $(this).html(text.replace(':trump:', image));
    

    注意:因为image 是一个字符串,所以您不需要.outerHTML

    如果messageBody 内部不仅仅是文本(它包含 HTML),那么您还需要更改这一行:

      var text = $(this).text();
    

    到这里:

      var text = $(this).html();
    

    所以完整的代码是:

    function wow() {
      $('.messageBody').each(function() {
          var text = $(this).html();
          var image = '<img class="emote" src="trump.png">';
          $(this).html(text.replace(':trump:', image));
      });
    }
    setInterval(wow, 1000);
    

    【讨论】:

      【解决方案2】:

      可以使用html(function),它也会循环所有实例

      $('.messageBody').html(function(_, existingHtml){
          var image = '<img class = "emote" src = "trump.png">'
          return existingHtml.replace(':trump', image);
      });
      

      使用 text() 去除任何 html 标签

      【讨论】:

      • 谢谢!我不明白每次出现另一条消息时如何让代码循环,谢谢大家!
      【解决方案3】:

      将您的代码更改为:

      function wow() {
        $('.messageBody').each(function() {
            var text = $(this).text();
            var image = '<img class = "emote" src = "trump.png">'
            $(this).html(text.replace(':trump:', image));
        });
      }
      setInterval(wow, 1000);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-19
        • 2017-07-26
        相关资源
        最近更新 更多