【问题标题】:Is there a way to replace a part of text with <img src> inside <p>?有没有办法用 <p> 中的 <img src> 替换部分文本?
【发布时间】:2019-06-26 13:58:48
【问题描述】:

我要做的是强制此代码用图像替换部分文本,如果他在段落中的页面上找到它,则它是“:•:”。

$("p").each(function () { 
    if ($(this).children().length == 0) {
        $(this).text($(this).text().replace(':•:').html('<img src = "http://lilpic.png" />')); 
    } 
});

但我最终得到的是,文本确实被替换了,但不是用原来的图像替换,而是用丑陋的原始 HTML 代码替换。我究竟做错了什么? 我最终需要的只是一个代码,它将标记“:•:”更改为图片。

【问题讨论】:

标签: jquery html image text replace


【解决方案1】:

要达到预期的效果:

  • 使用.html() 而不是.text()设置 html。 (请记住,它不再只是文字。)
  • 使用.replace(':•:', '&lt;img src="http://lilpic.png" /&gt;') 而不是.replace(':•:').html('&lt;img src = "http://lilpic.png" /&gt;')

注意:图像不会显示。 (因为http://lilpic.png 不是图片链接。

$("p").each(function() {

  if ($(this).children().length == 0) {
    $(this).html($(this).text().replace(':•:', '<img src="http://lilpic.png" />'));
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<p>Hello, this is some text :•:</p>

此外,您还可以对下面列出的代码进行一些其他改进。

$("p").each(function() {
  // Use $(this) instead of $(this), as it's faster
  var $this = $(this);

  if ($this.children().length == 0) {
    //Replace ':•:' with an image and store it in a variable called `newText`
    var $newText = $this.text().replace(':•:', '<img src="http://lilpic.png" />');

    //Set the new text with the replace image
    $this.html($newText);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p>Hello, this is some text :•:</p>

<p>Hello, this is some text :•:</p>

【讨论】:

  • 你是个巫师!非常感谢,现在可以了。由于某种原因,当我上次尝试时,它不起作用。也许我在某个地方犯了一个错误。
猜你喜欢
  • 1970-01-01
  • 2012-01-05
  • 1970-01-01
  • 2013-12-06
  • 1970-01-01
  • 2020-04-09
  • 1970-01-01
  • 1970-01-01
  • 2021-10-17
相关资源
最近更新 更多