首先,我们经常要用到点击一个下拉列表、li元素集某一项获取该项在整个下拉列表、li元素集的下标;这个看似简单的问题,初学者往往会有许困惑。
这里我们以单选按钮为例,场情:点击相应单选按钮出现该按钮下标;
</head>
<body>
<form name="form1">
<input type="radio" name="radioGroups">
<input type="radio" name="radioGroups">
<input type="radio" name="radioGroups">
<input type="radio" name="radioGroups">
<input type="submit">
</form>
<script>
window.οnlοad=function(){
//获取所有单选按钮;
var theForm = document.form1.radioGroups;
//js还支持这样写:document.forms[0].elements['radioGroups'];
//var j = theForm.length;
//alert(j);
for(i=0; i<theForm.length; i++){
theForm[i].onclick = (function(i){
return function(){
alert(i);
}
})(i);
}
}
//之前没能很好理解闭包原理,总会想当然写成:
for(i=0; i<theForm.length; i++){
theForm[i].onclick =function(i){
return (function(i){
alert(i);
})(i)
};
}
结果alert输出总是undefined;
</script>
</body>