【问题标题】:javascript to create a button with onclickjavascript创建一个带有onclick的按钮
【发布时间】:2012-01-28 20:59:40
【问题描述】:

我正在尝试使用 javascript 创建一个按钮,该按钮具有一个 onclick 事件,该事件调用在头部中定义的函数,该函数将相对于按钮的 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


【解决方案1】:

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

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

希望对你有帮助

【讨论】:

    【解决方案2】:
    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 问题:(
    • @zaftcoAgeiha 我不知道这意味着什么。你能解释一下你想要什么吗?编辑 :: 再次检查帖子。
    • 好的,我需要能够动态创建这个 并让它可点击
    • 我收到错误“未捕获的类型错误:无法读取未定义的属性 '1'”。我认为问题在于javascript认为“this”指的是js对象而不是html dom obj
    • @zaftcoAgeiha 这可能是因为我输入了“childNotes”而不是“childNodes”...代码有效。
    猜你喜欢
    • 2018-11-20
    • 1970-01-01
    • 2016-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    • 2023-01-12
    相关资源
    最近更新 更多