javascript to create a button with onclick

旧城冷巷雨未停 提交于 2019-12-17 10:46:34

问题


I'm trying to use javascript to create a button that has a onclick event that calls a function defined in the head that takes in as parameter a dom object relative to the button. how do i do this?

ex:

<html>
<head> <script>function blah(obj){alert(obj.value)}</script></head>
<body>
<button onclick="blah(this.parentNode.value);"></button>
</body>
</html>

javascript:

var newButton = document.createElement("button");
???

in the end i want the new button to be the same as the existing one.


回答1:


function createButton(context, func) {
    var button = document.createElement("input");
    button.type = "button";
    button.value = "im a button";
    button.onclick = func;
    context.appendChild(button);
}

window.onload = function() {
    createButton(document.body, function() {
        highlight(this.parentNode.childNodes[1]);
        // Example of different context, copied function etc
        // createButton(this.parentNode, this.onclick);
    });
};

Is that what you want?



来源:https://stackoverflow.com/questions/8650975/javascript-to-create-a-button-with-onclick

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!