插件的jquery函数:返回每个结果的问题

时间:2011-04-17 11:35:02

标签: jquery jquery-plugins z-index each

我在将下面的功能转换为插件时遇到问题,您能告诉我如何修复它吗?

功能,

function highest_Zindex(){

    var index_highest = 0;

    // more effective to have a class for the div you want to search and 
    // pass that to your selector
    $("div").each(function() {

        if($(this).css("zIndex") > 0)
        {
            // always use a radix when using parseInt
            var index_current = parseInt($(this).css("zIndex"), 10);

            if(index_current > index_highest) {
                index_highest = index_current;
            }
        }
    });

    return index_highest;
}

效果很好,

var test = highest_Zindex();
alert(test);

插件,

(function($){

    $.fn.extend({ 

        get_highest_Zindex: function(options) {

            var defaults = {
                increment: 10 // The opacity of the background layer.
            }

            var options = $.extend(defaults, options);


            var $cm = this.each(function(){


                var o = options;
                var object = $(this); // always return #document.

                var index_highest = 0;

                if(object.css("zIndex") > 0)
                {
                    // always use a radix when using parseInt
                    var index_current = parseInt(object.css("zIndex"), 10);
                    //alert(index_current);

                    if(index_current > index_highest) {
                        index_highest = index_current;
                    }
                }

            });

            return index_highest;

        }
    });

})(jQuery);

然后我会收到错误消息,

var test = $("div").get_highest_Zindex();
alert(test);
  

未定义index_highest

有什么想法吗?

感谢。

1 个答案:

答案 0 :(得分:1)

只需将var index_highest = 0;移到each声明之外:

(function($){
    $.fn.extend({ 
        get_highest_Zindex: function(options) {

            var defaults = { increment: 10 }
            var options = $.extend(defaults, options);
            var index_highest = 0;                         // <- here

            var $cm = this.each(function(){
                var o = options;
                var object = $(this);

                if (object.css("zIndex") > 0) {
                    var index_current = parseInt(object.css("zIndex"), 10);

                    if (index_current > index_highest) {
                        index_highest = index_current;
                    }
                }

            });

            return index_highest;
        }
    });
})(jQuery);