js select默认选中Option当前值

发布时间:2020-03-10编辑:脚本学堂
js select默认选中option当前值的方法,js获取select默认选中的Option并不是当前选中的值,来看这个例子。

1、js函数方法:
 

复制代码 代码示例:
<script>
function getDefaultSelectedOption(selectId, valIfNull) {
var dom, selectId = selectId.replace(/^#/, ''), opts;
try {
opts = document.getElementById(selectId).getElementsByTagName('option');
for (var i in opts) {
if (opts[i].defaultSelected) {
dom = opts[i];
break;
}
}
} catch (e) {
}
return dom||valIfNull;
}
</script>

例子,js select默认选中
 

复制代码 代码示例:
<body>
<select id="sel">
<option value="1">1</option>
<option value="2" selected="">2</option>
<option value="3">3</option>
</select>
<button id="btn">test</button>
<script>
function getDefaultSelectedOption(selectId, valIfNull) {
var dom, selectId = selectId.replace(/^#/, ''), opts;
try {
opts = document.getElementById(selectId).getElementsByTagName('option');
for (var i in opts) {
if (opts[i].defaultSelected) {
dom = opts[i];
break;
}
}
} catch (e) {
}
return dom||valIfNull;
}
</script>
<script>
document.getElementById('btn').onclick = function () {
alert((getDefaultSelectedOption('sel1', {})).value);
};
</script>
</body>

使用jquery获取$('#sel option[defaultSelected]'),可一直返回空。

要求:
select控件初始化的值,非select当前选中的值,初始化的值不随select值改变,当select值改变后,初始化的值是不会变的。