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

查看:149
本文介绍了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?

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.

推荐答案

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天全站免登陆