如何在自定义jquery插件中使用$(this)

How to use $(this) in custom jquery plug-in

这是我的代码

$('#J_todayComm').myScroll({
    ajaxUrl: $(this)
});

我想得到$(this) -> $('#J_todayComm'),但它是$(doucmen)

我的插件代码myScroll.js

$.fn.myScroll = function (options) {
    var s = $.extend({
        debug: false,
        threshold: 65,
        loading: false,
        ajaxUrl: '',
        ajaxMethod: 'GET',
        ajaxData: {},
        loadSuccess: function () {
        },
        template: function () {
            console.error("Need Template");
        }
    }, options);
    console.log(s.ajaxUrl); //I want it is $('#J_todayComm')
    // jquery对象
    var $self = this;
    // 原生DOM对象
    var self = this[0];
    ......
    function getDate() {
        if (!s.ajaxUrl) {
            console.error('Need url');
            return '';
        }
        $.ajax(s.ajaxUrl, {
            method: s.ajaxMethod,
            data: s.ajaxData,
            dataType: 'json',
            success: function (res) {
                ...
            },
            error: function () {
                ...
            }
        });
    }

    return $self;

};

如何编写代码?谢谢大家。

要使 this 关键字引用选择器中的元素,您需要更改调用范围。您可以通过使用 each():

遍历元素来做到这一点
$('#J_todayComm').each(function() {
  var $el = $(this);
  $el.myScroll({
    ajaxUrl: $el.data('ajax-url'),
    // other settings...
  });
});

代码

$.fn.extend({
  myScroll:function(){
    console.log(this);//這是你的本物件了
  }
})

$('#J_todayComm').myScroll();

改变另一种方式来扩展 fn 然后你不依赖于 orign jquery 功能并且可以获得 this 你的对象(并且没有你的 options)。