gpt4 book ai didi

javascript - 表情符号不适用于(Safari 和 Chrome 浏览器)中的多个表情符号

转载 作者:行者123 更新时间:2023-11-29 21:38:30 25 4
gpt4 key购买 nike

我正在尝试使用 jquery 制作表情符号。但是我有多个表情符号的问题。我创建了这个 demo来自 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();
});

最佳答案

为此,您将需要正则表达式,因为 replace 中的标志(您的 ,"g")已被弃用,并且不会在所有浏览器上工作 (source) .

所以你需要用你的笑脸代码创建你的正则表达式:

var re = new RegExp(emotes[emoticon][i], 'g');

但是由于您的笑脸代码具有特殊字符,因此您需要对它们进行转义。为此,我从这个 answer 中提取了一段代码:

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]+"\"/>");

Working Demo

关于javascript - 表情符号不适用于(Safari 和 Chrome 浏览器)中的多个表情符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34089638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com