jQuery自定义函数

时间:2013-02-27 10:39:25

标签: jquery

为什么不会覆盖oldHeight的值?它仍然有oldHeight80而不是我作为参数传递的内容。即使我传递参数newHeight,它也不会覆盖它。但根据documentation,它会自动更新。这是代码:

( function($) {
$.fn.bad = function(callback) {
    var options;
    var settings = $.extend({
        "oldHeight":"80",
        "newHeight":"200"
    }, options);
    return this.each( function() {
        var that$ = $(this);
        that$.bind("mouseenter", function() {
            $(this).animate({ "height" : settings.newHeight+"px" });
        }).bind("mouseleave", function() {
            $(this).animate({ "height" : settings.oldHeight+"px" });
        });
    });
}
})(jQuery);
$(".box").bad({"oldHeight":"400"});

这个===> Fiddle

2 个答案:

答案 0 :(得分:1)

您使用var options;初始化带有null的“选项”,并使用空值扩展您的设置。

( function($) {
    $.fn.bad = function(options) {
            var settings = $.extend({
                "oldHeight":"80",
                "newHeight":"200"
            }, options);

    ...

这有效。

答案 1 :(得分:1)

尝试,

var settings = {};
var settings = $.extend(settings, {
    "oldHeight":"80",
    "newHeight":"200"
}, options);

您的函数需要接受options而不是callback(如果没有使用回调)。

所以你的代码将是,

(function($) {
$.fn.bad = function(options) {
    var settings = {};
    var settings = $.extend(settings, {
        "oldHeight":"80",
        "newHeight":"200"
    }, options);
    ...

Test