Jquery表情符号脚本只发现第一次出现笑脸

时间:2012-12-05 11:44:48

标签: jquery repeat emoticons

我正在运行一个非常基本的jQuery表情符号脚本来将笑脸文本更改为图像。 这很好用,但似乎只适用于第一次出现的笑脸。 因此,如果我写2个相同的笑脸,它只会将一个改为图像。

请参阅小提琴:http://jsfiddle.net/t6vaH/

这是JS

jQuery.fn.emoticons = function(icon_folder) {
/* emoticons is the folder where the emoticons are stored*/
var icon_folder = icon_folder || "../../../../images/forum/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=\""+icon_folder+"/face-"+emoticon+".png\" class=\"emoticonimg\" alt=\""+emotes[emoticon][i]+"\"/>","g");
        }
    }
    return html;
}
return this.each(function(){
    $(this).html(emoticons($(this).html()));
});
};

什么是修复此功能的最佳方法,以便在每次出现笑脸时都能使用,以便我可以重复一遍?

由于

1 个答案:

答案 0 :(得分:0)

众所周知,Javascript替换仅替换子串的第一个出现。您将需要使用正则表达式来实现您想要的目标。

var emotes = {
                "angel": Array(/\(A\)/g)
             };

正则表达式选项中的g指定您希望匹配模式的所有出现。