문제

I'm writing a jQuery plugin and am trying to use the $(this) selector in one of the parameters, but it's undefined.

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:

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:

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

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top