jquery - 有没有办法用里面替换部分文本
?
问题描述
我要做的是强制此代码用图像替换部分文本,如果他在段落中的页面上找到它,则它是':•:'。
$("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>
推荐阅读
- python - 为什么python中的这段代码会出现这个错误?TypeError: 'int' 类型的对象没有 len() 但我在列表中调用它
- sql - 如何将列中的所有字符串值替换为另一个值?
- p5.js - 我需要 p5.js 中的菜单
- reactjs - 无法在 nextJs 中读取 razorpay 支付的 null 属性“tagName”
- arrays - C 语言 - 基于作为参数传递的索引值调用函数 - 指向函数的指针数组
- linux - Shell 脚本的 echo 命令 -e 选项写入文件
- matlab - 如何在给定 Y 值的情况下找到 X 值并在绘图上显示点
- python-3.x - 气流 2.0 Docker 设置
- python - Gekko 示例 1b 使用不同形式的相同终端约束得到不同的结果
- html - 如何在 LARAVEL_7 中通过迁移发送多个复选框