[英]How to use '$(this)' in a jquery plugin parameters
我正在編寫一個jQuery插件,並嘗試在其中一個參數中使用$(this)選擇器,但未定義。
這是我的代碼:
$('.foo').loadMore({
onScreen: function() {
$(this).css('background-color', 'red');
}
})
這是我插件中的代碼:
$.fn.loadMore = function( options ) {
var settings = $.extend({
onScreen: function(){},
}, options);
return this.each(function(index, ele) {
settings.onScreen();
});
};
您必須使用正確的this
值調用onScreen
:
settings.onScreen.call(this);
如果您希望與內置的jQuery方法更加一致,則還可以傳遞index和element:
settings.onScreen.call(this, index, this);
參考: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/call
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.