
正文
html select用法总结
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
本文将介绍select 原生的常用方法,这些都是经过测试,兼容ie6到ie10,及chrome,火狐等,也就是说大部分浏览器都兼容。如果大家发现有不兼容的情况,可以跟我留言。
我们对基本的用法了如指掌后,jQuery、kissy这些框架用起来更方便。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>select用法总结</title>
</head>
<body>
<h3>select的常用方法</h3>
<hr/> <div>
<h3>默认选中某一项,使用option的selected属性</h3>
<select name="test" id="test1">
<option value="1">1</option>
<option value="2" selected>2</option>
<option value="3">3</option>
</select>
</div> <div>
<h3>js使某一项选中</h3>
<select name="test" id="test2">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<script>
var test2 = document.getElementById('test2');
test2.value='3';
//kissy用法
//S.one('#test2').val('3');
</script>
</div> <div>
<h3>事件绑定,获取选中项的值</h3>
<select name="test" id="test3">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<script>
var test3 = document.getElementById('test3');
test3.onchange = function(e){
//经常看到有的代码这样写this.options[this.selectedIndex].value
//其实不用那么复杂,this.value就可以取到当前选中项的值,所有浏览器都支持
var val = this.value; //var val = test3.value;
alert(val);
}
</script>
</div> <div>
<h3>获取选中项的index</h3>
<select name="test" id="test4">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<script>
var test4 = document.getElementById('test4');
test4.onchange = function(e){
var idx = this.selectedIndex; //从0开始
alert(idx);
}
</script>
</div>
<div>
<h3>获取选中项的text</h3>
<select name="test" id="test5">
<option value="1">text1</option>
<option value="2">text2</option>
<option value="3">text3</option>
</select>
<script>
var test5 = document.getElementById('test5');
test5.onchange = function(e){
var selOption = this.options[this.selectedIndex]; //var val = test3.value;
// ie,chrome 下调用 innerText 其他浏览器如firefox下调用 textContent
var text = selOption.innerText || selOption.textContent; //兼容性
//所有浏览器都支持w3c标准的innerHTML,如果text里有标签可以通过正则替换
var html = selOption.innerHTML;
alert(text);
alert(html);
}
</script>
</div> </body>
</html>
代码地址:http://jsfiddle.net/6o1fdvm0/ 大家可以在这里测试






