2

我正在开发一些小型聊天应用程序。我想在那里实现表情符号,所以当我点击一些表情符号时,它会出现在用户输入他的消息的文本区域中,当用户点击选择时,我希望表情符号出现在包含对话的 div 中。

经过一些变通方法后,我意识到用 div contenteditable="true" 替换 textarea 效果不太好,所以我确实用 ':' 包装了某些笑脸名称,例如 textarea 中的 :wink: 但我仍然需要替换 :wink: 与包含图像作为背景的真实跨度。

问题是我没有看到一种动态制作的方法,而是一个一个地做。

例如:

        if ($('.line:contains(":wink:")').length > 0) {
            var oldLineHTML = $('.line:contains(":wink:")').html();
            $('.line:contains(":wink:")').html(oldLineHTML.replace(/:wink:/gi, '<span class="wink></span>"'));

我有很多表情符号,所以执行这个非常耗费资源的功能会花费我很多,并且还会在维护期间给我带来很多问题。

我怎样才能动态地做到这一点?或者,也许您有更好的解决方案,需要重新设计……如果需要,我可以做到。

谢谢 }

4

4 回答 4

3
var testString = "test1 :smile: test2 :wink:";
alert(testString.replace(/:([^:]*):/g, '<span class="$1"></span>'));
于 2011-06-05T15:24:56.010 回答
0

我的建议是读取由冒号包裹的每个字符串:[something]:,然后将其转换为跨度。这样您就不必定义每个微笑,并且易于维护。

于 2011-06-05T15:12:11.210 回答
0

If you are doing this on page load, then you can do this in a $(document).ready(). Then you can use selector that you have $('.line:contains(":wink:")') and use the $each operator to loop over each one and perform the update. This will cover you for the page load. But if you refactor that $each code into a method, then you can call it each time the text is updated. I think this will give you the best in both cases. Something like this:

function replaceWinks(){
$('.line:contains(":wink:")').each(function(index) {
    //Replace the wink here
  });
}

$(document).ready(function(){
replaceWinks();
});

I would recommend replacing the winks server side for the page load though. It will be more performant. Also it will avoid content that changes when after the first view.

于 2011-06-05T15:23:18.500 回答
0

Jeaffrey Gilbert's idea is good, but I have another one that may be interesting: write down you winks the way you want(let's say [SmileName]), and when processing the text with jquery, read every one of them, and replace the [ with <div class=" then replace the ] sign, with "></div>, this way, you will end up like this:

using these smilies:

1- [smile]

2- [wink]

3- [shy]

will lead to the following markup

1- <div class="smile"></div>

2- <div class="wink"></div>

3- <div class="shy"></div>

and using CSS, you will give every class of them, a different background image, which is the smile image.

by utilizing this method, every div will lead to displaying your smilies, and you will write the code once, and end up using it wherever you want, without repeating yourself

于 2011-06-05T15:24:10.100 回答