使用JavaScript创建一个带有onclick事件的按钮

16
我正在尝试使用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");
???

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


你能解释一下为什么要这样做吗?也许有更好的解决方案适用于你正在做的事情。 - AlanFoster
它有点(不必要地)复杂,但我会试着解释。原始按钮将创建一堆东西并删除自己。在所创建的东西之中,还有另一个按钮,可以重新创建原始按钮,该按钮也可以创建另一堆东西,如此往复。 - WindowsMaker
2个回答

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);
    });
};

那是你想要的吗?


我认为它没有解决DOM问题,其中传递的参数是相对于按钮的。:( - WindowsMaker
@zaftcoAgeiha 我不知道那是什么意思。你能解释一下你想要什么吗?编辑:: 请再次检查帖子。 - AlanFoster
好的,我需要能够动态创建此 <button onClick="highlight(this.parentNode.childNodes[1])">highlight</button> 并使其可点击。 - WindowsMaker
我遇到了错误:“Uncaught TypeError: Cannot read property '1' of undefined”。我认为问题在于 JavaScript 认为“this”指的是 JS 对象而不是 HTML DOM 对象。 - WindowsMaker
可能是因为我打成了'childNotes'而不是'childNodes'... 代码是可以运行的。 - AlanFoster

1

你也可以使用内置的 setAttribute JavaScript 函数。

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

希望能有所帮助

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接