javascript 使用 onclick 创建按钮

问题描述 投票:0回答:3

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

例如:

<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");
???

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

javascript dom createelement
3个回答
38
投票
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);
    });
};

这就是你想要的吗?


1
投票

您还可以使用内置的 setAttrbute javascript 函数。

var newButton = document.createElement("button")
newButton.setAttribute("onclick", "blah(this.parentNode.value)")

希望对你有帮助


0
投票

var newButton = document.createElement("button")
newButton.setAttribute("onclick", "blah(this.parentNode.value)")

© www.soinside.com 2019 - 2024. All rights reserved.