- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试创建我的第一个 jQuery 插件,但收到错误 this.each is not a function
,它引用了这一行 return this.each(function() {
在 bindUi
方法。我以为this
引用“调用插件的 jQuery 对象”,在我的例子中是 #location
我在使用 $('#location').locationSearch()
创建插件时使用的节点, 正确的?我在页面加载时收到此错误。
这是我的插件代码:
(function($) {
var methods = {
init : function( options ) {
return this.each(function() {
var settings = {
//none yet
};
if ( options ) {
$.extend( settings, options );
}
methods.log('init');
//attach events
methods.bindUi();
});
},
destroy : function( ) {
return this.each(function(){ });
},
bindUi : function() {
return this.each(function() {
methods.log('bindUi');
this.click(function() {
methods.log('clicked');
});
});
},
log : function(text) {
if (window.console && window.console.log) {
window.console.log(text);
};
}
} // end methods
jQuery.fn.locationSearch = function(method) {
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.tooltip' );
}
};
})( jQuery );
如果我的每一种方法都需要使用return this.each(function() { ..
,我也有点困惑或者如果只有 init 和 destroy 方法使用它?
最佳答案
你必须打电话
methods.bundUi.apply(this);
在您的 init
方法中。
如果您只执行methods.bindUi()
,则bindUi
内的this
将引用methods
对象。
更新:
哦,我刚看到。您正在 each
循环内部调用methods.bindUi()
。然后 this
将引用当前的 DOM 元素。所以现在的问题是,你想在 bindUi
中引用什么?所有选定的元素,还是仅循环中的当前元素?
这里有两种可能性:
A:所有元素
init : function( options ) {
this.each(function() {
var settings = {
//none yet
};
if ( options ) {
$.extend( settings, options );
}
methods.log('init'); // <- this might be also better outside the loop
});
//attach events
methods.bindUi.apply(this); // <- called outside the each loop
return this;
}
(无需更改 bindUi
)
B:一个元素。 init
中的 each
循环内的 this
将引用当前的 DOM 元素。我们一次只处理一个元素,因此不需要在 bindUi
方法中使用 each
。 (仍然在 init
中使用 methods.bindUi.apply(this)
(但在循环内部,就像您已经拥有它一样))。但您无法再从外部调用 bindUi
(即您无法调用 .locationSearch('bindUi')
)。
bindUi : function() {
// don't need `each`, as `this` will refer to only one element.
methods.log('bindUi');
$(this).click(function() {
methods.log('clicked');
});
},
第三种解决方案确实是将 bindUi
函数内的 this
更改为 $(this)
。这肯定会起作用,但有两个“误解”:
.locationSearch('bindUi')
调用该函数,则 this
将已经是一个 jQuery 对象并调用 $(this)
是多余的。init
中的 each
循环调用该函数,则 this
将引用one DOM 元素。因此调用 $(this)
是必要的,但使用 each
循环遍历 one 元素是没有意义的。 I am also a little confused if every one of my methods needs to use return
this.each(function() { ..
or if only theinit
anddestroy
methods use it?
应通过 .locationSearch(method)
调用的每个方法都应返回此
。
关于jQuery 插件 'this.each is not a function',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5129438/
我是一名优秀的程序员,十分优秀!