2016-12-22 105 views
1

我寫了一些代碼,對於理解jQuery的原型對象jQuery.fn更好,但我想不通爲什麼它不工作:jQuery的原型繼承

jQuery.fn.appender = function(text) { 
    // i want every jQuery-Element to inherit a method called appender (I know that there is already "append" - this is just for learning). 
    this.each(function(index, element) { 
     $(this).append(text); 
    }) 
}; 

$("diveins").appender(); // nothing is happening 

回答

0

問題無關,與繼承。這是因爲您沒有爲您的功能提供text參數。 diveins也不是一個有效的選擇器。推測這應該是.diveins。最後請注意,您的each()循環是多餘的,因爲默認情況下,jQuery將在集合中的每個元素上應用append()方法。試試這個:

$.fn.appender = function(text) { 
 
    $(this).append(text); 
 
}; 
 

 
$(".diveins").appender('foo'); // note the addition of the parameter here
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="diveins"></div> 
 
<div class="diveins"></div> 
 
<div class="diveins"></div>

當降低到這個水平的函數只是成爲append()的包裝是有點多餘,但我以爲你要進一步的邏輯添加到它。