0

我正在尝试处理 jquery 插件中的可链接性,并且它适用于click 下面的 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);​

但是当我使用eachready在插件中时出现错误,例如,

$(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 不是函数 [中断此错误]

为什么我不能用eachor做到这一点ready?还是我做错了?

4

2 回答 2

0

我重申我的评论作为答案,以便您接受:

函数表达式不会像var f = function() { ... }命名函数声明那样被提升function f() { ... }。因此,在each示例中,设置在声明之前$cm调用。$this.child_1在您的第一个示例中,该函数是在单击时调用的,因此它在执行时已经被解析。

于 2012-04-16T13:20:53.310 回答
-1

不要$在你的插件上使用。它与 jQuery 对它的使用相冲突。使用别的东西,a也许。

于 2012-04-16T13:04:43.823 回答