2013-05-22 60 views
-1

我在使用非常虛擬的JavaScript代碼中的模塊模式時出現問題。模塊模式jQuery

此代碼是可以正常使用:

; 
var test = (function() { 
    var config = { 
     replacement: $('a') 
    }; 

    var init = function() { 
     config.replacement.click(function(){ 
      alert("hello"); 
     }); 
    } 

    return { 
     init: init 
    } 
})(); 

$(document).ready(test.init()); 

任何人都可以告訴我爲什麼我不能使用:

; 
var test = (function() { 
    var config = { 
     replacement: 'a' 
    }; 

    var init = function() { 
     $(config.replacement).click(function(){ 
      alert("hello world"); 
     }); 
    } 

    return { 
     init: init 
    } 
})(); 

$(document).ready(test.init()); 

相反,當我點擊我的網站的任何鏈接,這個代碼不工作一個jQuery對象作爲配置變量的「默認」初始化。

回答

1

$(a)在DOM就緒之前執行,可能在沒有a元素可訪問時執行。

在您的第一個示例中,該集合是在DOM就緒後構建的。

你可以把它變成不是函數...

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

@ user1648170護理鏈接我嗎? – alex

+0

我剛剛回答了代碼:) – user1648170

-1

那麼,爲什麼在這個例子中位於使用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); 
}); 

Official jQuery website

+0

如果仔細看*,您會看到這段代碼被封裝在'$(document).ready(function(){...});'中。此外,這不是對您的問題的答案 - 它應該是對原始問題的編輯。 – alex