javascript - 查找单词并替换为 div 中的标签 jQuery

标签 javascript jquery html

我有一个带有一些文本的 div,我正在尝试使用 jQuery 将该文本替换为 html 标签,但是,它将替换标签作为文本而不是 html 标签

以下是html结构

<h3>Rs.1410 / 30 Tablet(s) </h3>

我尝试过的JS是

$("h3").text(function () {
    return $(this).text().replace("Rs.", "<i class='fa fa-inr'></i>"); 
});

如果我尝试 .html() 那么它会替换该 div 中我不想要的所有内容。有人可以建议吗

谢谢

最佳答案

使用html()函数而不是 text()

$("h3").html(function () {
    return $(this).text().replace("Rs.", "<i class='fa fa-inr'></i>"); 
});

来自文档

A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set.

关于javascript - 查找单词并替换为 div 中的标签 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40739387/

相关文章:

javascript - 使用 jQuery 将点击事件添加到类中

javascript - 追加后的 Jquery CSS 宽度

javascript - 从 json 动态生成复选框列表

css - 有没有办法让 float 的 div 标签采用它从内容中获得的实际高度

html - nav 或只是 ul 之间的 seo 区别

javascript - 将 <a> 标签格式化为 Markdown

javascript - 如何使用动画jquery缓慢打开div

javascript - onbeforeunload 中的 Ajax 第一次不工作

javascript - 多个字符串与 indexOf() 匹配

javascript - jQuery:如何查找具有相同 src 的元素