如何在同一页面中的多个jQuery插件之间隔离功能 [英] How to isolate functionalities between multiple jQuery Plugins in Same Page
问题描述
如果我在同一页面上拥有多个相同插件的实例,那么我该如何分隔功能.例如.在此演示 http://jsfiddle.net/3jwAK/中,我有一个插件"editor
"附加一个模拟某些插件/小部件按钮的链接,单击该链接将在textarea
上附加一行.
If I have more than 1 instance of the same plugin on the same page how can I separate functionality. eg. in this demo http://jsfiddle.net/3jwAK/, I have a plugin "editor
" that appends a link simulating some plugin/widget button, that when clicked will append a line to the textarea
.
当前的问题是它仅针对最后一个textarea
The problem with it currently is it only targets the last textarea
代码看起来像
JS
(function($) {
$.fn.editor = function(options) {
var helpers = {
rand: function() {
return Math.round(Math.random() * 20);
}
};
return this.each(function() {
$this = $(this);
var div = $("<a>", {
text: "Add Random Number",
href: "#",
click: function() {
$this.val( $this.val() + "\n" + helpers.rand() );
}
});
$this.before(div);
});
}
})(jQuery);
HTML
<textarea name="txtArea1" cols="50" rows="6" id="editor1"></textarea>
推荐答案
问题是变量$this
在该函数的每次运行中都必须是本地副本.在其前面放置var
.
The problem is the variable $this
needs to be a local copy in each run of that function. Put var
in front of it.
var $this = $(this);
已更新: http://jsfiddle.net/3jwAK/1/
这篇关于如何在同一页面中的多个jQuery插件之间隔离功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!