會有問題,因爲this
在jQuery插件的外部指的是jQuery對象/集合本身,而不是該集合的單個元素。因此,而不是:
jQuery.fn.do_para = function() {
var section_effect = jQuery(this);
var height = section_effect.height();
alert(height);
//do something with height
}
您應該改用:
jQuery.fn.do_para = function() {
// if you don't want to return the collection
// omit the 'return' (but this will break
// the traditional jQuery chaining if you do):
return this.each(function(){
// within the each() method 'this' refers
// to each individual element of the
// collection passed to the plugin:
var section_effect = jQuery(this);
var height = section_effect.height();
alert(height);
//do something with height
});
}
究其原因,問題指的是整個集合的是,當一個jQuery方法被用作吸附材料(使用沒有方法傳遞參數)它將引用集合中的第一個元素,並從第一個元素返回值。
如果你想要的,因爲某些原因,檢索值的數組,而不是你也可以使用:) jQuery.fn.do_para =功能({VAR = section_effect jQuery的(本);
// here we use the map() method to iterate over
// the collection and, from each element in the
// collection, return the height:
var height = section_effect.map(function(){
$(this).height();
// here we use get() to turn the jQuery map into
// an Array:
}).get();
alert(height);
//do something with height
}
順便說一下,如果,該插件的代碼中,你要使用jQuery
–一個別名,以節省打字,如果不出意外–那麼你就可以代替撰寫你的插件以如下方式,使用Immedately調用的函數表達:
// the argument to the function is the
// alias with which you refer to
// jQuery:
(function ($) {
$.fn.do_para = function(){
return this.each(function(){
var section_effect = $(this);
// rest of your code..
});
});
// passing jQuery into the function:
})(jQuery);
參考書目: