这两行代码完美无缺 -
var html = $this.find('pre').html().replace(':mellow:','<img src="http://i2.ifrm.com/html/emoticons/mellow.gif">');
$this.find('pre').html(html);
(它找到字符串:mellow:并用特定图像替换它。)
我遇到的困难是试图把它变成我不必重复这两行代码50或60次的东西。 (我在那个初学者阶段,当你可以用三个代码完成时,你最终会编写数百行代码。)
如何将上述内容转换为可以处理多个表情符号的内容(例如:mellow:,:lol:等)并找出相应的图像(与代码名称相同,减去::)。
伪代码示例 -
var emoCodes = [
':mellow:', ':lol:', ':ninja:'
];
var html = $this.find('pre').html().replace(+emoCodes+,'<img src="http://i2.ifrm.com/html/emoticons/+CorrespondingImage+.gif">');
$this.find('pre').html(html);
好的,谢谢。
答案 0 :(得分:2)
使用数组你是在正确的轨道上,因为你需要查找表情符号代码和相应的图像,你可以创建一个对象数组:
var emoCodes = [
{code: ':mellow:', img: '<img src="http://i2.ifrm.com/html/emoticons/mellow.gif">'},
{code: ':lol:', img: '<img src="http://i2.ifrm.com/html/emoticons/lol.gif">' },
{code: ':ninja:', img: '<img src="http://i2.ifrm.com/html/emoticons/ninja.gif">' }
];
然后使用code
和img
属性循环遍历数组:
for(var i=0: i<emoCodes.length; i++) {
var html = $this.find('pre').html().replace(RegExp(emoCodes[i].code,"g"),emoCodes[i].img);
$this.find('pre').html(html);
}
此方法允许您将任何代码应用于任何图像,即使code
未嵌入其网址中也是如此。
答案 1 :(得分:2)
这应该这样做:
var emoCodes = [
':mellow:', ':lol:', ':ninja:'
];
var $this = $("body");
emoCodes.forEach(function(code) {
var image = '<img src="http://i2.ifrm.com/html/emoticons/' + code.replace(/:/g, "") + '.gif">';
$this.find('pre').html(function(index, html) {
return html.replace(new RegExp(code, "g"), image);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre>:mellow::mellow::lol::ninja:</pre>