[英]How to get variable defined inside of jQuery custom plugin
I am working on a custom jQuery plugin. 我正在开发一个自定义jQuery插件。 I need to access the options passed in the first function within the second function. 我需要访问第二个函数中第一个函数中传递的选项。
The problem is if I declare settings outside of these functions, it gets mixed up when I have multiple instances of this plugin initialized on the same page. 问题是,如果我在这些函数之外声明设置,则当我在同一页面上初始化了该插件的多个实例时,设置会变得混乱。
(function($) {
$.fn.MyCombobox = function(options) {
var settings = $.extend({
selector: '.myselector'
}, options);
};
$.fn.MyCombobox.clear = function() {
$(settings.selector).find('input').val('');
};
}(jQuery));
One approach would be to set .data()
at .MyCombobox
一种方法是在.MyCombobox
上设置.data()
(function($) { $.fn.MyCombobox = function(options) { var settings = $.extend({ selector: '.myselector' }, options); this.data("options", settings); return this }; $.fn.clear = function() { console.log(this.data("options") || {/* default settings here */}) }; }(jQuery)); $("div").MyCombobox().clear();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.