工作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>