关于在ie7,8等低版本浏览器的获得<select>元素的值的的兼容性问题

通过如下代码展示解决该兼容性方案!

第一种:check2函数里面的方案可以针对option没有设置value和设置了value的情况
<html>
<head>
<meta charset="utf-8">
<title>select</title>
</head>

<body>
<!-- A种情况 option未设置value -->
<select name="select" id="select1">
<option selected="selected">Test1</option>
<option >Test2</option>
</select>

<!-- B种情况 option设置value -->
<select name="select2" id="select2">
<option value="Test1" selected="selected">Test1</option>
<option value="Test2">Test2</option>
</select>

<input type="button" value="我要试试" onclick="check1()">

<input type="button" value="我要试试" onclick="check2()">
<script>


function check1() {
//当上面option里没有设置value属性时
var value = document.getElementById("select1").options[document.getElementById("select1").options.selectedIndex].value,
text = document.getElementById("select1").options[document.getElementById("select1").options.selectedIndex].text;
console.log(value);
console.log(text);

}
function check2() {
//当上面option里设置value属性时
var value = document.getElementById("select2").options[document.getElementById("select2").options.selectedIndex].value,
text = document.getElementById("select2").options[document.getElementById("select2").options.selectedIndex].text;
console.log(value);
console.log(text);

}

</script>
</body>

</html>

第二种:check1函数里面的方案可以针对option设置了value的情况


<html>
<head>
<meta charset="utf-8">
<title>select</title>

</head>

<body>
<select name="select1" id="select1">
<option value="Test1" selected="selected">Test1</option>
<option value="Test2">Test2</option>
</select>

<input type="button" value="我要试试" onclick="check1()">
<script>


function check1(){
//当上面option里设置了value属性时
var select = document.getElementById("select1").value;
console.log(select);
console.log(document.getElementById("select1").options.selectedIndex);
}

</script>
</body>

</html>

posted @ 2015-10-26 22:09  jcbtl  阅读(852)  评论(0编辑  收藏  举报