我创建类似这样的 JQuery Widgets
<script type="text/javascript">
(function ($) {
$.widget("cb.bacon", {
_create: function() {
var self = this,
o = self.options,
el = self.element;
// Some code
},
_bacon: function() {
var self = this,
o = self.options,
el = self.element;
// Some code
},
_smokey: function() {
var self = this,
o = self.options,
el = self.element;
// Some code
}
});
})(jQuery);
</script>
我最终总是必须在我创建的每个函数中声明 self
、options
、element
。
我是否缺少一些基本的理解,或者我真的必须一直这样做吗?
最佳答案
您根本不必这样做,这只是为了更容易访问函数内部的内容。
当您在 jQuery 函数中使用回调时,self
变量非常有用,其中 this
将设置为您正在操作的元素。例如:
$('.bacon').each(function(){ $(this).css('background', self.getBackground()); });
变量o
和el
只是减少了输入。如果变量 self
或引用 this
未更改,则可以从以下位置访问 options
和 element
属性:直接指向对象。
关于javascript - 我是否需要在 JQuery Widget 中每个函数的开头定义 'self' 、 'element' 等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19842499/