js中的基本事件
直接在标签中使用事件句柄
回调函数,对于当前程序来说,sayhello函数被称为回调函数(callback函数)
回调函数的特点,自己把函数写出来,但是这个函数不是自己负责调用,有其他的程序负责调用该函数。
<script type="text/javascript">
function sayhello(){
alert("hello js");
}
</script>
<input type="button" value="hello" onclick="sayhello()"/>
使用纯js完成事件的注册
第一步,获取按钮对象,document.getElementById()(getElementById通过id获取对象)
document内置对象,可以直接使用,代表整个html页面。widow代表整个浏览器。
第二步,给按钮对象的onclick属性赋值。
匿名函数:没有方法名字,这个函数在页面打开的时候只是注册,不会调用,在click事件发生之后才会调用。
<input type="button" value="hello2" id="btn" />
<input type="button" value="hello3" id="btn2" />
<input type="button" value="hello4" id="btn3"/>
<script type="text/javascript">
function doSome(){
alert("do some");
}
var btnobj = document.getElementById("btn");
btnobj.onclick = doSome;
var btnobj2 = document.getElementById("btn2");
btnobj2.onclick = function(){
alert("test......")
}
//简写
document.getElementById("btn3").onclick = function(){
alert("test22222......");
}
</script>