我試着寫我的第一個jquery插件。jquery插件 - 這個ID是undefined
JS代碼
$('#test').existInTip();
(function($){
$.fn.existInTip = function(){
console.log($(this).attr('id'));
}
})(jQuery);
,但我得到一個未定義的錯誤?怎麼了?
在此先感謝!
Peter
我試着寫我的第一個jquery插件。jquery插件 - 這個ID是undefined
JS代碼
$('#test').existInTip();
(function($){
$.fn.existInTip = function(){
console.log($(this).attr('id'));
}
})(jQuery);
,但我得到一個未定義的錯誤?怎麼了?
在此先感謝!
Peter
您應該確保在使用腳本之前聲明並解析腳本。嘗試交換兩個代碼塊。
$(this)
可能與實例化對象一起使用。
$.fn.existInTip
是一個函數。
您正在嘗試在聲明插件之前使用existInTip
。改變順序:
(function($){
$.fn.existInTip = function(){
console.log($(this).attr('id'));
}
})(jQuery);
$('#test').existInTip();
如果這個代碼是在你的頁面的<head>
部分,你也希望把最後一行document ready
處理器中:
$(document).ready(function() {
$('#test').existInTip();
});
一兩件事:裏面一個jQuery插件,this
已經是jQuery對象,所以沒有必要包裝它:
$.fn.existInTip = function(){
console.log(this.attr('id')); // Or this[0].id
}