我想在一個jQuery插件chainability工作,它工作正常使用jQuery click
below chainability,jQuery插件的每個並準備
$(document).ready(function(){
$('.call-parent').parent_child({
target: '.element'
});
$('.call-child-1').click(function(){
$(this).parent_child().child_1();
return false;
});
$('.call-child-2').click(function(){
$(this).parent_child().child_2();
return false;
});
});
(function($) {
$.fn.extend({
parent_child: function(options) {
var defaults = {
target:''
}
var options = $.extend(defaults, options);
var o = options;
var $this = this;
var $cm = this.click(function(ei) {
alert('parent');
$this.child_1();
return false;
});
$this.child_1 = function() {
alert('child 1');
};
$this.child_2 = function() {
alert('child 2');
};
return $cm;
}
})
})(jQuery);
,但我有錯誤,當我使用each
或在插件ready
,例如,
$(document).ready(function(){
$('.call-parent').parent_child({
target: '.element'
});
$('.call-child-1').click(function(){
$(this).parent_child().child_1();
return false;
});
$('.call-child-2').click(function(){
$(this).parent_child().child_2();
return false;
});
});
(function($) {
$.fn.extend({
parent_child: function(options) {
var defaults = {
target:''
}
var options = $.extend(defaults, options);
var o = options;
var $this = this;
var $cm = this.each(function(ei) {
alert('parent');
$this.child_1();
return false;
});
$this.child_1 = function() {
alert('child 1');
};
$this.child_2 = function() {
alert('child 2');
};
return $cm;
}
})
})(jQuery);
錯誤消息,
$ this.child_1不是一個函數[打破這個錯誤]
爲什麼我不能做到這一點與each
或ready
?或者我做錯了嗎?
函數表達式不會被掛起,所以當你設置'$ cm'時,'$ this.child_1'還不存在。 – Mathletics 2012-04-16 13:05:07
明白了。謝謝回覆。 – laukok 2012-04-16 13:10:28