有没有办法在<p>内用<img src>替换一部分文本?

灵敏的Sirin

我要执行的操作是如果该代码在段落的页面上用图像替换了':•:'文本的一部分,则将其强制执行。

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

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

克里斯·快乐

为了达到预期的效果:

  • 使用.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>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

有没有办法用 p5 绘制一个 matter.js 组合?

有没有办法用MongoDB替换Many()?

有没有办法更改标签内的 src-url?

有没有办法从二进制内容设置 img 或音频/视频的 src 属性

有没有办法只更改 QTextEdit 中的一部分文本?

有没有办法在 Outlook 中显示 <img> 替代文本属性?

有没有办法用 php 一致地阅读电子邮件正文的一部分(回复)

有没有办法在JS中一次更改少量图像的src?

有没有办法用css3和html5的新实现隐藏div的一部分?

删除img src的一部分

有没有办法使用 google doc API 用样式文本替换文本?

有没有办法在 javascript 或 p5.js 中使文本溢出?

有没有办法用熊猫中的列表替换所有列值?

有没有办法用另一个替换列表中的索引?

有没有办法用sed进行多次替换,而不用链接替换项?

有没有办法用JavaScript中的单字母替换双字母?

有没有办法用逻辑语句替换字符串(不是,和,或)

有没有办法用小时替换今天的日期?

PDFTron WebViewer - 有没有办法用评论框替换回复框?

有没有办法用多个字符替换空格?

有没有办法用同名变量替换字符串?

有没有办法用 Pandas 中的字符串值替换 True/False?

有没有办法用相邻的值替换列表中的特定值?

有没有办法用空行将多行文本分开?

有没有办法用文本更新 Tkinter 画布?

有没有办法用 React 返回纯文本响应,根本不包含 HTML?

有没有办法用jsPDF将表格单元格的文本居中?

有没有办法用代码创建一个segue

有没有办法用Dlang一次分配多个变量?