2015-09-27 55 views
1

我想通過構造函數通過JavaScript創建Button。一切正常,但onclick事件啓動後立即加載頁面,而不是點擊按鈕後。Javascript onclick事件在重新加載頁面時開始

function Button(text) { 
    this.button = document.createElement('button'); 
    this.button.id = text; 
    this.button.innerHTML = text; 
    this.button.style.width = 100; 
    this.button.style.height = 30; 
    document.body.appendChild(this.button); 
}; 

b1 = new Button('button1'); 
b1.onclick = alert('hello'); 

回答

0

它將在加載時開始,因爲您使用alert('hello')明確地調用它。

更好的「包裝」它:

b1.onclick = function() { 
    alert('hello') 
} 

這樣你分配一個functionb1.onclick事件,該功能將在點擊按鈕調用。

0

在您的代碼中,您調用alert,並將其返回值設爲b1.onclick

function Button(text) { 
    this.button = document.createElement('button'); 
    this.button.id = text; 
    this.button.innerHTML = text; 
    this.button.style.width = 100; 
    this.button.style.height = 30; 
    document.body.appendChild(this.button); 
}; 

b1 = new Button('button1'); 
b1.onclick = function() { 
    //Handle click here 
    alert("hello"); 
}; 

b1.onclick應該是一個函數。

0

當你說b1.onclick = alert("hello");,它認爲你想要alert()函數返回去b1.onclick,所以它會運行該函數並找出。你想要的是這樣的:

b1.onclick = function(){ 
    alert("hello"); 
}; 

這是在點擊b1時將被稱作實際的函數對象。

相關問題