2015-06-27 162 views
3

接收「文本」和「onclick函數」的按鈕我想做我在標題中所說的。 我嘗試這樣做:函數創建通過參數

function createButton(func, text){ 
    var butt = document.createElement('BUTTON'); 
    var btTxt = document.createTextNode(text); 
    btTxt.style.color = '#006633'; 
    btTxt.style.fontWeight = 'bold'; 
    butt.onclick = func; 
    butt.appendChild(btTxt); 
    butt.style.margin = '5px'; 
    document.body.appendChild(butt); 
} 

這:

createButton(doSomething, click to do something); 

但它不工作:/

有人嗎?

回答

3

您需要設置樣式的按鈕,而不是TextNode對象:

function createButton(func, text) { 
 
    var butt = document.createElement('BUTTON'); 
 
    var btTxt = document.createTextNode(text); 
 
    butt.style.color = '#006633'; 
 
    butt.style.fontWeight = 'bold'; 
 
    butt.onclick = func; 
 
    butt.appendChild(btTxt); 
 
    butt.style.margin = '5px'; 
 
    document.body.appendChild(butt); 
 
} 
 

 
createButton(doSomething, 'click to do something'); 
 

 
function doSomething() { alert('Hello'); }