我正在尝试使用jquery制作一个表情符号。但我对多个表情有问题。我从演示中创建了这个jsfiddle.net。
如果用户编写了不同的多个表情符号,那么jquery代码可以正常工作,但是如果用户写了两个或两个以上的微笑,比如:),那么jquery代码只显示第一个表情符号,其他表情符号就不会显示。这里有人能帮我吗?
JS
jQuery.fn.emoticons = function(icon_folder) {
/* emoticons is the folder where the emoticons are stored*/
var icon_folder = icon_folder || "emoticons";
//var settings = jQuery.extend({emoticons: "emoticons"}, options);
/* keys are the emoticons
* values are the ways of writing the emoticon
*
* for each emoticons should be an image with filename
* 'face-emoticon.png'
* so for example, if we want to add a cow emoticon
* we add "cow" : Array("(C)") to emotes
* and an image called 'face-cow.png' under the emoticons folder
*/
var emotes = {"smile": Array(":-)",":)","=]","=)"),
"sad": Array(":-(","=(",":[",":<"),
"wink": Array(";-)",";)",";]","*)"),
"grin": Array(":D","=D","XD","BD","8D","xD"),
"surprise": Array(":O","=O",":-O","=-O"),
"devilish": Array("(6)"),
"angel": Array("(A)"),
"crying": Array(":'(",":'-("),
"plain": Array(":|"),
"smile-big": Array(":o)"),
"glasses": Array("8)","8-)"),
"kiss": Array("(K)",":-*"),
"monkey": Array("(M)")};
/* Replaces all ocurrences of emoticons in the given html with images
*/
function emoticons(html){
for(var emoticon in emotes){
for(var i = 0; i < emotes[emoticon].length; i++){
/* css class of images is emoticonimg for styling them*/
html = html.replace(emotes[emoticon][i],"<img src=\"http://www.oobenn.com/"+icon_folder+"/face-"+emoticon+".png\" class=\"emoticonimg\" alt=\""+emotes[emoticon][i]+"\"/>","g");
}
}
return html;
}
return this.each(function(){
$(this).html(emoticons($(this).html()));
});
};
$(document).ready(function(){
$(".posted").emoticons();
});发布于 2015-12-04 14:56:57
要做到这一点,您将需要正则表达式,因为replace中的标志(您的replace)是不推荐的,并且不会在每个浏览器(来源)上工作。
因此,您需要使用您的笑脸代码创建regexp:
var re = new RegExp(emotes[emoticon][i], 'g');但是,由于您的笑脸代码有特殊的字符,您需要转义它们。为此,我从这个回答中提取了一段代码
function escape(smiley){
return smiley.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}最后,您可以使用replace替换所有的笑脸,即使有几次相同的笑脸:
var escaped = escape(emotes[emoticon][i]);
var re = new RegExp(escaped, 'g');
html = html.replace(re,"<img src=\"http://www.oobenn.com/"+icon_folder+"/face-"+emoticon+".png\" class=\"emoticonimg\" alt=\""+emotes[emoticon][i]+"\"/>");工作演示
https://stackoverflow.com/questions/34089638
复制相似问题