javascript用onclick创建一个按钮 [英] javascript to create a button with onclick

查看:30
本文介绍了javascript用onclick创建一个按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

例如:

<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.

推荐答案

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

这就是你想要的吗?

这篇关于javascript用onclick创建一个按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆