[英]How to use '$(this)' in a jquery plugin parameters
I'm writing a jQuery plugin and am trying to use the $(this) selector in one of the parameters, but it's undefined. 我正在编写一个jQuery插件,并尝试在其中一个参数中使用$(this)选择器,但未定义。
Here's my code: 这是我的代码:
$('.foo').loadMore({
onScreen: function() {
$(this).css('background-color', 'red');
}
})
And here's the code in my plugin: 这是我插件中的代码:
$.fn.loadMore = function( options ) {
var settings = $.extend({
onScreen: function(){},
}, options);
return this.each(function(index, ele) {
settings.onScreen();
});
};
You have to call onScreen
with the correct this
value: 您必须使用正确的this
值调用onScreen
:
settings.onScreen.call(this);
If you want to be more in line with the built-in jQuery methods, you can pass the index and element as well: 如果您希望与内置的jQuery方法更加一致,则还可以传递index和element:
settings.onScreen.call(this, index, this);
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call 参考: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/call
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.