Javascript javascript用onclick创建一个按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8650975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:55:36  来源:igfitidea点击:

javascript to create a button with onclick

javascriptdomcreateelement

提问by WindowsMaker

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?

我正在尝试使用 javascript 创建一个按钮,该按钮具有 onclick 事件,该事件调用在头部中定义的函数,该函数将相对于按钮的 dom 对象作为参数。我该怎么做呢?

ex:

前任:

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

javascript:

javascript:

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

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

最后,我希望新按钮与现有按钮相同。

回答by AlanFoster

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?

那是你要的吗?