2012-04-18 24 views
0

我正在編寫一些oo風格的js。當我的頁面加載時,它會執行兩次我的login()函數,而我想觸發login()的事件偵聽器根本不起作用。任何幫助將不勝感激。這裏是我的代碼:javascript oo編程語法對於菜鳥的幫助

(function(window, undefined) { 
var document = window.document, 
    navigator = window.navigator, 
    location = window.location; 
//build the login button 
var DA = { 
    width : '70px', 
    height : '20px', 

    createLoginButton : function(){ 
     var a = document.createElement('a'); 
     a.style.width = this.width; 
     a.style.height = this.height; 
     a.style.cursor = 'pointer'; 
     var div = document.createElement('div'); 
     div.id = 'da_login_button'; 
     div.onclick = DA.login(); 
     div.innerHTML = "client login"; 
     div.style.width = this.width; 
     div.style.height = this.height; 
     div.style.backgroundColor = '#59724A'; 
     div.style.color = 'white'; 
     div.style.border = '4px solid #6B5D49'; 
     div.style.padding = '3px'; 
     div.style.textAlign = 'center'; 
     a.appendChild(div); 
     return a; 
    }, 

    //write the button to the dom 
    writeLoginButton : function(){ 
     var dest = document.getElementById('digital_arborist_login'); 
     dest.style.width = this.width; 
     dest.style.height = this.height; 
     var theButton = DA.createLoginButton(); 
     dest.appendChild(theButton); 
     theButton.addEventListener("click", DA.login(), false); 
    }, 

    //detect ssl 
    isSecure : function(){ 
     if (location.protocol === 'https:') { 
      return true; 
     } else { 
      return false; 
     } 
    }, 

    // the login function 
    login : function(){ 
     alert('href: '+location.href+'<br />protocol: '+location.protocol); 
    }, 

}; 
window.DA = DA; 
})(window) 

// start the magic 
DA.writeLoginButton(); 

Here is the web page where I'm testing my code.

+0

當我檢查頁面時,我得到一個警報,會發生什麼? – 2012-04-18 15:25:57

回答

1

更改此:

theButton.addEventListener("click", DA.login(), false); 

到:

theButton.addEventListener("click", DA.login, false); 

這:

div.onclick = DA.login(); 

到:

div.onclick = DA.login; 

您想在每種情況下將函數本身分配爲回調。實際上,您正在執行函數並將函數調用的結果指定爲回調函數......這就是您的「登錄」方法在啓動時運行兩次以及點擊事件無法正常運行的原因。

您還應該從第一行中刪除undefined參數。 undefined是javascript中的一個關鍵字,我真的很驚訝你沒有從中得到語法錯誤。它應該看起來像:

(function(window) { 
+1

'undefined'可能是關鍵字,但大多數瀏覽器都會讓您爲其分配值。將'undefined'添加到參數列表確保它確實設置爲'undefined'。演示:http://jsfiddle.net/9Lv7Y/ – 2012-04-18 15:38:16

+1

這個伎倆!謝謝!此外,我刪除了div.onclick =,因爲我不需要兩個點擊處理程序來處理同一個按鈕。 – ShadeTreeDeveloper 2012-04-18 15:39:23

+0

我將undefined關鍵字簡單地用作複製jQuery的過程。我不知道我爲什麼要這麼做,現在我知道了。感謝您的評論。 – ShadeTreeDeveloper 2012-04-18 15:40:40

2
theButton.addEventListener("click", DA.login(), false); 

在這條線的變化DA.login()只是DA.login。當您執行DA.login()時,您將login()函數(即undefined)的結果傳遞給click處理程序,而不是函數本身。

它應該是:

theButton.addEventListener("click", DA.login, false); 

編輯:div.onclick = DA.login();應該div.onclick = DA.login;,也。