关于动态给input控件添加事件的问题

robyjeffding 2009-04-12 05:58:57
我有5个input控件,类型都是text ,我想写一个javascript函数,让每个的控件的onblur(或者onfocus)事件都是一样的,该如何实现?
可不可以这样:var input=document.getElementsByTagName('input')
for(var i=0;i<input.length;i++){
input[i].blur=某个函数名;
}
...全文
158 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
robyjeffding 2009-04-15
  • 打赏
  • 举报
回复
多谢高手指点!
knifewei 2009-04-12
  • 打赏
  • 举报
回复
关注
s_liangchao1s 2009-04-12
  • 打赏
  • 举报
回复

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> new document </title>
<script type="text/javascript">
<!--
function addEventHandler(){
var oInput = document.getElementsByTagName("input");
for(var i = 0; i < oInput.length; i++ ){
if(oInput[i].type == "text"){
oInput[i].onblur = function(){
alert("Success Blur")
}
}
}
}
//-->
</script>
</head>

<body>
<input type="text" id="" /><br/>
<input type="text" id="" /><br/>
<input type="text" id="" /><br/>
<input type="text" id="" /><br/>
<input type="text" id="" /><br/>
<input type="button" value="添加事件" onclick="addEventHandler()" />

</body>
</html>

sohighthesky 2009-04-12
  • 打赏
  • 举报
回复
上面的方法添加事件后会移除对象之前已经存在的事件,可以用下面的方法来解决:

if(obj.attachEvent) {
obj.attachEvent("onchange",function() {//IE
otherfunction(params);//这里可以给其实方法传参,也可以直接调用其它方法
});
} else if(obj.addEventListener) {//FF
obj.addEventListener("change",function() {
otherfunction(params);
},false);
}
sohighthesky 2009-04-12
  • 打赏
  • 举报
回复

for(var i=0;i <input.length;i++){
input[i].onblur=某个函数名;
}

这样应该就可以了吧

87,996

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧