首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Jquery emoticon脚本仅查找首次出现的smiley

Jquery emoticon脚本仅查找首次出现的smiley
EN

Stack Overflow用户
提问于 2012-12-05 19:44:48
回答 1查看 779关注 0票数 1

我正在运行一个非常基本的jQuery表情脚本来将笑脸文本转换为图像。这很有效,但似乎只在第一次出现微笑时有效。所以如果我写2个相同的笑脸,它只会把一个变成一个图像。

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

这是JS

代码语言:javascript
复制
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()));
});
};

修复这个函数的最好方法是什么,以便对每个笑脸符号的出现都有效,这样我就可以重复它们了?

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-12-05 19:48:45

众所周知,Javascript replace只替换第一个出现的子字符串。您需要使用正则表达式来实现您想要的功能。

代码语言:javascript
复制
var emotes = {
                "angel": Array(/\(A\)/g)
             };

正则表达式选项中的g指定要匹配模式的所有匹配项。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13722537

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档