我试图用这个jsfiddle上的纯文本替换所有的笑脸图像:
正如你所看到我试图使用:
$("code").each(function () {
var a = ['<img class="smile" src="http://static.yamma.org/images/icons/smile.png">', '<img class="laugh" src="http://static.yamma.org/images/icons/laugh.png">'],
b = [":)", ":D"],
inner = $(this).children('img').size();
for (var d = 0; d < inner; d++) {
var c = $(this).html();
var e = c.replace(a[d], b[d]);
$(this).text(e)
}
});
但这只取代了每张图片的第一个笑脸。 然后在已经更换的笑脸之后,没有被替换的笑脸返回:
&amp;lt;img class="smile" src="http://static.yamma.org/images/icons/smile.png"&amp;gt; &amp;lt;img class="laugh" src="http://static.yamma.org/images/icons/laugh.png"&amp;gt;
我不明白为什么要添加&amp; amp; lt;
有解决方案吗?有没有人知道如何将某些笑脸图像替换为纯文本。
答案 0 :(得分:1)
为了解决问题的最后部分,我可以为您提供替代方法:
var emotions = {
'smile' : ':)',
'laugh' : ':D'
};
var img = $('code img').each(
function(){
var s = this.src.split('/').pop(),
emo = s.substring(0,s.lastIndexOf('.'));
if (emo == 'laugh' || emo == 'smile'){
console.log(emotions[emo]);
$(this)
.replaceWith('<span class="emotion">' + emotions[emo] + '</span>');
}
});
答案 1 :(得分:0)
您是要尝试替换整个图像标记还是将文本笑脸作为图像标记的文本?我不确定第二个选项是否有意义,但它看起来像你的代码正在做什么。以下是一些代码:http://jsfiddle.net/44mqG/5/
以下代码用新的span标记替换整个标记:http://jsfiddle.net/44mqG/6/
答案 2 :(得分:0)
但这只取代了每张图片的第一个笑脸
String.replace
以这种方式工作。为了替换所有出现的情况,您需要将RegExp
替换为全局标记(g
),或者循环执行。
我不明白为什么要添加&amp; amp; lt;
因为你将其作为html(var c = $(this).html();
),并以文字形式回复($(this).text(e)
)
答案 3 :(得分:0)
这是你的答案:
$('img').each(function(){
switch($(this).attr('class')){
case "smile":
$(this).replaceWith(':)');
break;
case "laugh":
$(this).replaceWith(':D');
break;
}
});
这是DEMO