gpt4 book ai didi

javascript - 如何在jquery插件参数中使用 '$(this)'

转载 作者:行者123 更新时间:2023-12-03 12:40:20 24 4
gpt4 key购买 nike

我正在编写一个 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方法,你也可以传递索引和元素:

settings.onScreen.call(this, index, this);

引用:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

关于javascript - 如何在jquery插件参数中使用 '$(this)',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23555406/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com