<span style="color:#ff0000;">.getElementById和</span><span style="color: rgb(255, 0, 0); font-family: Arial, Helvetica, sans-serif;">.getElementsByName方法如下:</span>
.html代码如下:
<!DOCTYPE html>
<html>
<head>
<title>选取元素</title>
<style type="text/css">
#result{width:400px;border:1px solid #bc0;line-height:24px;padding-top:5px;padding-left:5px;font:11pt;color:gray;font-weight:bold;display:none;margin:0 auto}
body{text-align:center}
</style>
<script type="text/javascript">
function showResult(){
<span style="color:#ff0000;">var result = document.getElementById('result');
var objs = document.getElementsByName("favorate")</span>;<span style="color: rgb(255, 0, 0); font-family: Arial, Helvetica, sans-serif;">//获得的是数组</span>
var str = "";
for(var i = 0 ; i < objs.length ; i++){
if(objs[i].checked)
str += objs[i].value+"<br/>";
}
result.innerHTML = str;
result.style.display= "block";
}
</script>
</head>
<body >
兴趣爱好:<input type="checkbox" value="足球" checked="checked" name="favorate"/>足球
<input type="checkbox" value="篮球" name="favorate"/>篮球
<input type="checkbox" value="音乐" name="favorate"/>音乐
<input type="checkbox" value="电影"name ="favorate"/>电影
<input type="button" value="显示结果" οnclick="showResult()"/>
<div id="result">
</div>
</body>
</html>
.getElementsByTagName()方法
<!DOCTYPE html>
<html>
<head>
<title>选取元素</title>
<style type="text/css">
#result{width:400px;border:1px solid #bc0;line-height:24px;padding-top:5px;padding-left:5px;font:11pt;color:gray;font-weight:bold;display:none;margin:0 auto}
body{text-align:center}
</style>
<script type="text/javascript">
function showResult(){
var result = document.getElementById("result");
var str = "";
var objs = <span style="color:#ff0000;">document.getElementsByTagName("input");//获得的是数组
</span>
for(var i = 0 ; i < objs.length ; i++){
if(objs[i].type == "checkbox" && objs[i].checked)
str += objs[i].value +"<br/>";
}
result.innerHTML = str;
result.style.display= "block";
}
</script>
</head>
<body >
兴趣爱好:<input type="checkbox" value="足球" checked="checked" name="favorate"/>足球
<input type="checkbox" value="篮球" name="favorate"/>篮球
<input type="checkbox" value="音乐" name="favorate"/>音乐
<input type="checkbox" value="电影"name ="favorate"/>电影
<input type="button" value="显示结果" οnclick="showResult()"/>
<div id="result">
</div>
</body>
</html>
实现效果是一致的,如下: