使用Javascript / Jquery替换图像 [英] Replacing word(s) with image using Javascript/Jquery

查看:136
本文介绍了使用Javascript / Jquery替换图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个:

  $(。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 / tImg)
});

Demo



为什么你的工作不能按预期工作是因为你用图像,而不是它的具体内容。您可以使用 .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'/>));
}
});


I have this:

$(".forum-threadview-post-text:contains(':P')").html(":P").replaceWith("<img src='http://website.com/images/emotes/tongue.png' />");

It is supposed to take any instances of ':P' and replace it with an emoticon image. However, it takes posts with :P and replaces the entire post with that image. How can I replace only the :P.

解决方案

Try

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 )
});

Demo

Reason why yours doesn't work as expected is because you are replacing the matched element(s) with the image, not the specific content of it. You can use .html( function(index, oldhtml) ) to get the html of each element and replace it.

Or:

$(".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 / Jquery替换图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆