js(含有for if函数)
1.在定义变量时,尽可能让变量的访问范围最小化
2.弹出单选性别,嵌套for和if函数
<script type="application/javascript">
function student(){
var genderInput=document.getElementsByName("gender");
for (var i=0;i<genderInput.length;i++) {
if(genderInput[i].checked){
gender=genderInput[i].value;
break;
}
}
alert("性别:"+gender)
}
</script>
- genderInput[i].checked checked属性表示当前组件是否被选中
3.弹出多选选项爱好,嵌套for和if else
<script type="application/javascript">
function student(){
var hobbyInput=document.getElementsByName("hobby");
var hobby="";
for(var i=0;i<hobbyInput.length;i++){
if(hobbyInput[i].checked){
if(hobby!=""){
hobby=hobby+","+hobbyInput[i].value;
}
else{
hobby=hobbyInput[i].value;
}
}
}
alert("爱好:"+hobby);
}
</script>
- length表示数组的长度