javascript 调用onclick动作的几种方式。

var ebutt=document.getElementById("ebutt");
    if(window.addEventListener){ // Mozilla, Netscape, Firefox
        ebutt.addEventListener('click', ea('Hello,My function name is ea!'), true);
    } else { // IE
        ebutt.attachEvent('onclick', ea('Hello,My function name is ea!'));
    }
    和
function eb1(){
var ebutt=document.getElementById("ebutt");
ebutt.onclick=function(){
eb2()
};
}
以上都是直接执行了。
因为我要修改的是a标签的onclick事件的内容,所以又用了修改href的内容,来代替修改onclick.结果可以了,不过其它的没有href怎么为呢?
后来想想,觉得自己很傻,href是标签的一个属性,那onclick又何尝不是呢。onclick既然是标签的一个属性,肯定有设置标签属性的方法,于是乎查看了一个html的手册,终于找到了setAttribute()方法。(笔者曾经为这个事件纠结一阵子,没想到是如此的简单,看来还是对api不熟悉的缘故)
完整代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
input {300px;height:50px;line-height:50px;}

</style>
<script type="text/javascript">

function ea(str){
    alert(str);
    var ebutt=document.getElementById("ebutt");
    ebutt.setAttribute("onclick","eb('Hello,My function name is ebbbbbbb!')");
}   

function eb(str){
    alert(str);
    var ebutt=document.getElementById("ebutt");
    ebutt.setAttribute("onclick","ea('Hello,My function name is eaaaaaaa!')");
}
</script>
</head>
<body>
<div>
<input id="ebutt" type="button" onclick="ea('Hello,My function name is eb!');" value="测试动态绑定onclik事件" />
</div>
</body>
</html>

原文地址:https://www.cnblogs.com/jqy518/p/3042863.html