里面替换部分文本

?

,jquery,html,image,text,replace"/>

首页 > 解决方案 > 有没有办法用里面替换部分文本

?

问题描述

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

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

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

标签: jqueryhtmlimagetextreplace

解决方案


要达到预期的结果:

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

注意:图像不会显示。(因为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>


推荐阅读