码迷,mamicode.com
首页 > 编程语言 > 详细

javascript如何给事件处理函数传递参数

时间:2015-12-24 14:47:40      阅读:815      评论:0      收藏:0      [点我收藏+]

标签:

javascript如何给事件处理函数传递参数:
在应用中可能需要给注册的事件处理函数传递参数,但是会发现好像无法实现直接传递,下面就简单介绍一下如何给事件处理函数传递参数。

先看一段代码实例:

<!DOCTYPE html> 
<html> 
<head> 
<meta charset=" utf-8"> 
<meta name="author" content="http://www.softwhy.com/" />
<head>
<title>蚂蚁部落</title> 
<script type="text/javascript"> 
function mytest(num){
  alert(num); 
}
window.onload=function(){
  var bt=document.getElementById("bt");
  bt.onclick=mytest(1);
}
</script> 
</head> 
<body> 
<input type="button" value="点击测试效果" id="bt">
</body> 
</html> 

以上代码的本意是当点击按钮的时候能够为函数传递一个参数,不过这是错误的,因为函数直接执行了。
正确写法:
方式一:

<!DOCTYPE html> 
<html> 
<head> 
<meta charset=" utf-8"> 
<meta name="author" content="http://www.softwhy.com/" />
<head>
<title>蚂蚁部落</title> 
<script type="text/javascript"> 
function mytest(num){
  alert(num); 
}
window.onload=function(){
  var bt=document.getElementById("bt");
  bt.onclick=function(){
    mytest(1)
  }
}
</script> 
</head> 
<body> 
<input type="button" value="点击测试效果" id="bt">
</body> 
</html> 

将函数嵌套在事件处理函数中调用,这样就可以传递参数了。
方式二:

<!DOCTYPE html> 
<html> 
<head> 
<meta charset=" utf-8"> 
<meta name="author" content="http://www.softwhy.com/" />
<head>
<title>蚂蚁部落</title> 
<script type="text/javascript"> 
function mytest(num){
  alert(num); 
}
</script> 
</head> 
<body> 
<input type="button" value="点击测试效果" onClick="mytest(1)"/>
</body> 
</html> 

此种方式和方式一的原理是一样的。

原文地址是:http://www.softwhy.com/forum.php?mod=viewthread&tid=8234

更多内容可以参阅:http://www.softwhy.com/javascript/

javascript如何给事件处理函数传递参数

标签:

原文地址:http://www.cnblogs.com/zhadanren/p/5072948.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!