使用.replace用HTML替换文本?

时间:2016-10-16 23:16:05

标签: javascript jquery html

我想用jQuery用图像替换文本。我一直在使用.replace函数替换更多文本的文本。如何用html标签替换文本,例如< img>标签

这是我的代码:

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>

3 个答案:

答案 0 :(得分:5)

如果您使用.html代替.text,则可以使用 $(this).text(text.replace(':trump:', image.outterHTML)); 。改变这一行:

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

到此:

image

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

如果 var text = $(this).text(); 不仅包含文本内容(包含HTML),那么您还需要更改此行:

  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);

所以完整的代码是:

@Headers({"Accept: application/json", "Content-Type: application/json"})
@POST("task/create/")
Call<StandardTaskResponse> createNewTask(@Body Task newTask);

答案 1 :(得分:2)

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

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

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

答案 2 :(得分:1)

将您的代码更改为:

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);