我有这个:
$(".forum-threadview-post-text:contains(':P')").html(":P").replaceWith("<img src='http://website.com/images/emotes/tongue.png' />");
它应该采用“:P”的任何实例并将其替换为表情符号图像。但是,它接收带有 :P 的帖子并用该图像替换整个帖子。我怎样才能只替换 :P。
最佳答案
尝试
var tImg = "<img src='http://website.com/images/emotes/tongue.png' />";
$(".forum-threadview-post-text:contains(':P')").html(function (_, html) {
return html.replace(/:P/g , tImg )
});
您的无法按预期工作的原因是您用图像替换了匹配的元素,而不是图像的具体内容。您可以使用 .html( function(index, oldhtml) )获取每个元素的 html 并替换它。
或者:
$(".forum-threadview-post-text:contains(':P')").contents().each(function () {
if(this.nodeType === 3 && /:P/g.test(this.nodeValue)) {
$(this).parent().html(this.nodeValue.replace(/:P/g,"<img src='http://placehold.it/10x10' />"));
}
});
关于javascript - 使用 Javascript/Jquery 用图像替换单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20135868/