2017-05-15 60 views
1

使用$(本)這是我的代碼如何在自定義jQuery插件

$('#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; 

}; 

如何編寫代碼? Thx大家。

回答

1

要使this關鍵字引用選擇器中的元素,您需要更改呼叫的範圍。你可以做的是通過元素迭代使用each()

$('#J_todayComm').each(function() { 
    var $el = $(this); 
    $el.myScroll({ 
    ajaxUrl: $el.data('ajax-url'), 
    // other settings... 
    }); 
}); 
+0

Thx,你的靈感來自我 –

0

代碼

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

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

變化的其他方式來延長FN那麼你不依賴於生產地的jQuery funtion並能得到你對象的this(沒有你的options)。

+0

Thx,樓上的也許是我想要的 –