最近,在学习,html和javascript,在学到select标签时,发现在获取<select>选取的item时,有值得注意的地方:
在js利用代码中获取<select>被选中项时,如果通过 document.getElementsByName(); 来获取select时,有时候会找不到<select>;
而通过 document.getElementById();来获取<select>时,则不会发生找不到对象的情况。
学习所敲源码如下:(Html_Study.html)
<!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>Html_1_1</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<style type="text/css">
#txtshow {
width: 32px;
}
</style>
</head>
<body>
<script type="text/javascript">
function myFun_1() { //获取选择了那一个item,分别通过select标签的onfocus(),onchange(),onblur()来调用
var selobj;
var selind;
//var showval;
var showtxt;
//selobj = document.getElementsByName("selList_1");
selobj = document.getElementById("selList_1");
selind = selobj.selectedIndex;
//showval = selobj.options[selind].value;
showtxt = selobj.options[selind].text;
alert("亲,你选择了:" + showtxt);
}
function addItem() { //为select增加item
var basesel;
basesel = document.getElementById("selList_1");
basesel.add(new Option("Item-" + (parseInt(basesel.length) + 1).toString(), "Item-" + (parseInt(basesel.length) + 1).toString()));
}
function showSize() { //显示select标签的item的总条数
var basesel;
basesel = document.getElementById("selList_1");
document.getElementById("txtshow").value = basesel.length;
}
</script>
<form action="Html_Study.html" method="get"></form>
<select name="selList_1" id="selList_1" οnchange="javascript: myFun_1();">
<!--
<select name="selList_1" id="selList_1" οnfοcus="javascript: myFun_1();">
<!--
<select name="selList_1" id="selList_1" οnblur="javascript: myFun_1();">
-->
<option value="Item-1">Item-1</option>
<option value="Item-2">Item-2</option>
<option value="Item-3">Item-3</option>
<option value="Item-4">Item-4</option>
<option value="Item-5">Item-5</option>
<option value="Item-6">Item-6</option>
</select>
<label>Item条数:</label>
<input type="text" id="txtshow" value="6"/>
<input type="button" name="addIte" value="新增Item" οnclick="javascript: addItem(); showSize()" />
<br/>
</body>
</html>