如何更新jQuery函数以替换源而不返回?
给定以下插件: 作者希望您如何使用以下内容如何更新jQuery函数以替换源而不返回?,jquery,jquery-plugins,Jquery,Jquery Plugins,给定以下插件: 作者希望您如何使用以下内容 $.fn.emoticon = function(theText) { var imagePath = "emotes/"; var newText = theText; for( var a in emoticons.emoticon ) { emoticon = emoticons.emoticon[a]; for( var emote in emoticon.emotes ) {
$.fn.emoticon = function(theText) {
var imagePath = "emotes/";
var newText = theText;
for( var a in emoticons.emoticon ) {
emoticon = emoticons.emoticon[a];
for( var emote in emoticon.emotes ) {
emote = RegExp.escape(emote);
newText = newText.replace( new RegExp( emote, 'gi' ), '<img src="'+imagePath + emoticon.image + '" />');
}
}
return newText;
};
它返回:
"Hello <img src="emotes/shock.png" /> World"
“你好,世界”
有没有办法让它替换传递的元素?就像在更新中找到匹配的位置一样?有点像你如何将tipsy应用到你想要的元素:$('example-1').tipsy()代码>
想法?感谢正如roberkules所说,这是一个糟糕的jquery插件,下面的函数将替换jquery元素的html,然后返回这个(jquery元素)以允许链接
$.fn.emoticon = function(theText) {
var imagePath = "emotes/";
var newText = theText;
for( var a in emoticons.emoticon ) {
emoticon = emoticons.emoticon[a];
for( var emote in emoticon.emotes ) {
emote = RegExp.escape(emote);
newText = newText.replace( new RegExp( emote, 'gi' ), '<img src="'+imagePath + emoticon.image + '" />');
}
}
return this.each(function() {
$(this).html(newText);
});
};
将导致函数返回$('body'),html为:
<body>Hello <img src="emotes/shock.png" /> World</boby>
你好,世界
“this”在本上下文中可能是有问题的元素,但我如何更新以实际替换我传递的内容?尝试使用$(this).replace(newElement)代码>也许?对我来说,它看起来像一个糟糕的插件。这种用法毫无意义。它只关心传递给它的文本,而不关心jQuery选择器(它被完全忽略)。我要么寻找另一个插件,要么自己创建一个(基于他的搜索/替换方法),函数也应该被包装,比如(Function($){/*Function goes here*/})(jQuery);
<body></boby>
$('body').emoticon('Hello :0 World');
<body>Hello <img src="emotes/shock.png" /> World</boby>