2017-05-06 34 views
0

早上好!我試圖創建一個函數來使用jQuery在網頁上生成一組按鈕。我的示例代碼如下。按鈕被創建(耶),但價值,onclick等參數不使用(噓)。請能有更好的技能,我告訴我在我的代碼中的錯誤?非常感謝你的幫助!我打我的頭靠在這裏牆上...通過函數參數使用jQuery構建按鈕

var buttonBar = document.getElementById("ButtonBar"); 
function genButton (butName, butLabel, action) { 
    $('#buttonBar').append 
     ('<input type="button" 
     name=butName 
     value = butLabel 
     onclick = action>'); 
} 

genButton('butAsIs', 'Buy As Is', 'funAsIs()'); 

function funAsIs() { 
    window.alert("Buy Me Pressed"); //TestCode 001 
} 

回答

0

隨着你的代碼只是附加的字符串作爲參數,而不是你的變量。 對於正確的工作,你可能會寫

$('#buttonBar').append 
    ('<input type="button" name="' + butName + '" value ="' + butLabel + '" onclick="' + action + '">'); 

或者使用ES6語法與${expressions}

0

工作examaple要創建你應該使用document.createElement("input");新的輸入。

// Let's create an input 
    var element = document.createElement("input"); 

分配新的屬性是很容易通過這種方式

element.type = 'button'; 
    element.value = butLabel; 
    element.name = butName; 

添加onclick事件是有點棘手。我們需要將它包裝在函數中,然後我們可以調用它。

element.onclick = function() { 
    action(actionParams); 
    }; 

要生成新的按鈕,我們將使用:

function generateButton(butName, butLabel, action, actionParams) { ... } 

我們可以調用這個函數的例子是這樣的:

generateButton('yourName', 'yourLabel', popAlert, { alertText: 'hello!', randomStuff: 'random' }) 

action的是,我們通過一個函數名作爲論據。現在請記住添加() - 這裏的重要部分。

actionParams是我們的action的論點。在我們的例子中,它只是javascript對象{ alertText: 'hello!', randomStuff: 'random' },你可以傳遞任何你想要的東西。

最後我們將新輸入添加到我們的#result選擇器。

這裏是工作示例。運行代碼片段以查看它的工作原理。

function generateButton(butName, butLabel, action, actionParams) { 
 
    // Let's create an input 
 
    var element = document.createElement("input"); 
 
    
 
    // Now we assign 
 
    element.type = 'button'; 
 
    element.value = butLabel; 
 
    element.name = butName; 
 
    element.onclick = function() { 
 
    action(actionParams); 
 
    }; 
 

 
    // Now we append 
 
    var result = document.getElementById("result"); 
 
    result.appendChild(element); 
 
} 
 

 
function popAlert(params) { 
 
    alert(params.alertText); 
 
    console.log(params.randomStuff); 
 
}
#result { 
 
    padding: 20px; 
 
    border: 1px solid #eee; 
 
} 
 

 
input[type="button"] { 
 
    margin: 2px; 
 
}
<input type="button" value="click me to generate new button!" onclick="generateButton('yourName', 'yourLabel', popAlert, { alertText: 'hello!', randomStuff: 'random' })" /> 
 

 
<div id="result"></div>