6
我是一名中級前端JS開發人員,我嘗試使用Chris Coyyer概述的模塊模式here。使用「模塊模式」時jQuery點擊事件不起作用
但是,當我在設置中存儲jQuery選擇器時,我無法使用它觸發單擊事件。看到下面的代碼與我的意見...任何幫助非常感謝!
var s,
TestWidget = {
settings: {
testButton: $("#testing")
},
init: function() {
s = this.settings;
this.bindUIActions();
},
bindUIActions: function() {
console.log(s.testButton); // This works: [context: document, selector: "#testing", constructor: function, init: function, selector: ""…]
//This doesn't work - why?????
s.testButton.click(function() {
//Why isn't this triggered?
alert('testButton clicked');
});
/*This works, obviously:
$('#testing').click(function() {
alert('testButton clicked');
});
*/
}
};
$(document).ready(function() {
TestWidget.init();
});
+1「過度使用模式」 – Bergi
我認爲op只是簡單地遵循CSS技巧來理解模式。也許手頭有更大的任務?如果意圖是通過模塊化理解封裝,我推薦閱讀addy osmani的設計模式。 – stavarotti
在所有內容之後,將腳本塊置於頁面底部可以解決此問題。這將使代碼完全放置在模塊內,而不會泄漏到全局名稱空間。 –