2012-12-05 65 views
1

我正在運行一個非常基本的jQuery表情符腳本來將笑臉文字轉換爲圖像。 這個效果很好,但似乎只能在笑臉的第一次出現時才起作用。 所以如果我寫2 x表情是相同的,它只會改變一個圖像。Jquery表情符號腳本只發現第一個笑臉

見琴: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())); 
}); 
}; 

請告訴我修復此功能的笑臉的每個實例工作,所以我可以重複他們的最好方法是什麼?

感謝

+0

更換隻捕獲第一次發生。你需要使用正則表達式 – Popnoodles

回答

0

的Javascript取代是衆所周知的,只更換子的第一 occurence。你將需要使用正則表達式來實現你想要的。

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

在正則表達式選項g指定要匹配的模式出現的所有。