模块模式jQuery



我在一个非常虚拟的javascript代码中使用模块模式有问题。

下面的代码运行正常:

;
var test = (function () {
    var config =  {
        replacement: 'a'
    };
    var init = function () {
        $(config.replacement).click(function(){
            alert("hello world");
        });
    }
    return {
        init: init
    }
})();
$(document).ready(test.init());

相反,这段代码不工作,当我点击我的网站的任何链接:

;
var test = (function () {
    var config =  {
        replacement: $('a')
    };
    var init = function () {
        config.replacement.click(function(){
            alert("hello");
        });
    }
    return {
        init: init
    }
})();
$(document).ready(test.init());

任何人都可以告诉我为什么我不能使用jQuery对象作为配置变量的"默认"初始化

$(a)在DOM准备好之前执行,可能是在没有a元素可访问的情况下。

在第一个示例中,该集合是在DOM就绪之后构造的。

你可以把它变成一个函数…

var config =  {
    replacement: function() { return document.links; }
};

那么,为什么在这个例子中位于jQuery官方网站使用jQuery选择器是为默认配置变量工作?

var feature = (function () {
    var $items = $("#myFeature li");
    var $container = $("<div class='container'></div>");
    var $currentItem = null;
    var urlBase = "/foo.php?item=";
    var createContainer = function () {
            var $i = $(this);
            var $c = $container.clone().appendTo($i);
            $i.data("container", $c);
        },
        buildUrl = function () {
            return urlBase + $currentItem.attr("id");
        },
        showItem = function () {
            $currentItem = $(this);
            getContent(showContent);
        },
        showItemByIndex = function (idx) {
            $.proxy(showItem, $items.get(idx));
        },
        getContent = function (callback) {
            $currentItem.data("container").load(buildUrl(), callback);
        },
        showContent = function () {
            $currentItem.data("container").show();
            hideContent();
        },
        hideContent = function () {
            $currentItem.siblings().each(function () {
                $(this).data("container").hide();
            });
        };
    $items.each(createContainer).click(showItem);
    return {
        showItemByIndex: showItemByIndex
    };
})();
$(document).ready(function () {
    feature.showItemByIndex(0);
});

jQuery官方网站

最新更新