怎么用JS获取按钮的序号

Mandy_周 2011-10-13 06:37:12
有4个OK的按钮
<input type="button" name="tname" value="OK">
<input type="button" name="tname" value="OK">
<input type="button" name="tname" value="OK">
<input type="button" name="tname" value="OK">
请问怎么用JS获取按钮的序号?
就是点第一个OK按钮显示你点了第一个按钮。。。
请问怎么弄啊
...全文
420 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
Mandy_周 2011-10-13
  • 打赏
  • 举报
回复
谢谢LS的
不过已经给分了
实在不好意思
咸鱼boris 2011-10-13
  • 打赏
  • 举报
回复

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title> 无标题文档</title>
<script type="text/javascript">
function clickEvt(obj){
var before = 0;
while(obj){
if(obj.type == "button")before ++;
obj = obj.previousSibling;
}
alert(before);
}
</script>
</head>

<body>
<input type="button" name="tname" value="OK" onclick="clickEvt(this)">
<input type="button" name="tname" value="OK" onclick="clickEvt(this)">
<input type="button" name="tname" value="OK" onclick="clickEvt(this)">
<input type="button" name="tname" value="OK" onclick="clickEvt(this)">
</body>
liangws 2011-10-13
  • 打赏
  • 举报
回复

<input type="button" name="tname" value="OK" onclick="fn(this)">
<input type="button" name="tname" value="OK" onclick="fn(this)">
<input type="button" name="tname" value="OK" onclick="fn(this)">
<input type="button" name="tname" value="OK" onclick="fn(this)">



var els = document.getElementsByName("tname");

function fn(e){
for (var i = els.length;i-- ; ) {
if(els[i] == e){
alert("第" + (i+1) + "个元素");
break;
}
}
}
Mandy_周 2011-10-13
  • 打赏
  • 举报
回复
就是得到数组啊。
a[2]不就是点了第3个嘛
我的意思是整个代码怎么写
Left_you 2011-10-13
  • 打赏
  • 举报
回复
window.document.getElementsByName("tname")
这样得到的是数组
Mandy_周 2011-10-13
  • 打赏
  • 举报
回复
大哥们,JS啊用getElementByName啊
Left_you 2011-10-13
  • 打赏
  • 举报
回复
试试,或者
<input type="button" name="tname" value="OK" onclick="alert('第1个');">
<input type="button" name="tname" value="OK" onclick="alert('第2个');">
<input type="button" name="tname" value="OK" onclick="alert('第3个');">
<input type="button" name="tname" value="OK" onclick="alert('第4个');">
Left_you 2011-10-13
  • 打赏
  • 举报
回复
试试
<input type="button" name="tname" value="OK" id="1" onclick="alert(this.id);">
<input type="button" name="tname" value="OK" id="2" onclick="alert(this.id);">
<input type="button" name="tname" value="OK" id="3" onclick="alert(this.id);">
<input type="button" name="tname" value="OK" id="4" onclick="alert(this.id);">

87,990

社区成员

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

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