前幾天發了一篇關於javascript獲取select值的方法,后來發現有另一種實現方法,所以就都發出來比較一下:
方法一:通過獲取option標簽的value值來確定:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>select</title>
</head>
<body>
<form id="form1" name="form1">
<select id="s1" name="s1" onChange="printTest();">
<option selected="selected" value="0" >選項一</option>
<option value="1">選項二</option>
<option value="2">選項三</option>
</select>
<input type="submit" value="button"/>
</form>
<script type="text/javascript">
function printTest() {
var oSelect = document.getElementById('s1');
var ind = oSelect.value;
var val = oSelect.value;
var tex = oSelect.options[oSelect.value].text;
alert('ind = ' + ind + '\nval = ' + val + '\ntext = ' + tex);
}
</script>
</body>
</html>
這個方法需要為每個option標簽定義一個value,而且value的值應為“0 1 2…”這樣排序。
方法二:用javascript原裝的selectIndex屬性實現:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>select</title>
</head>
<body>
<form id="form1" name="form1">
<select id="s1" name="s1" onChange="printTest();">
<option selected="selected" value="1" >選項一</option>
<option value="2">選項二</option>
<option value="3">選項三</option>
</select>
<input type="submit" value="button"/>
</form>
<script type="text/javascript">
function printTest() {
var oSelect = document.getElementById('s1');
var ind = oSelect.selectedIndex;
var val = oSelect.options[oSelect.selectedIndex].value;
var tex = oSelect.options[oSelect.selectedIndex].text;
alert('ind = ' + ind + '\nval = ' + val + '\ntext = ' + tex);
}
</script>
</body>
</html>
這種方法就相對比較簡單,也不需要設置value值了。
然后再說下如何實現自定義select樣式,實現這個樣式我認為需要實現4點功能:
1.select的效果,就是點擊右邊按鈕打開下拉框,點擊下拉框內容或右邊按鈕或頁面其他位置會收回下拉框;
2.模擬select里的select屬性不要用到value值的,這里可以考慮用 li 標簽的index屬性來代替;
3.模擬select選中某項時會記錄該項value值,可以結合第二點把value值放在變量里;
4.模擬form表單里提交時會把select當前選中的option標簽的value值傳送給后台,還有復位的功能。
先寫到這,未完待續!
