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

时间:2014-05-09 01:46:06

标签: javascript jquery jquery-plugins

我正在编写一个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();
    });
};

1 个答案:

答案 0 :(得分:1)

您必须使用正确的onScreen值致电this

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