JS检索下拉列表框中被选项目的索引号(selectedIndex)
selectedIndex API
-
JavaScript 提供了找到select ID索引号的方法,它反映了第一个或最后选择的索引 元件,这取决于值 multiple,注意,该值为 -1 指示未选择任何元素。
-
selectedIndex 属性可设置或返回下拉列表中被选选项的索引号,若允许多重选择,则仅会返回第一个被选选项的索引号
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS检索下拉列表框中被选项目的索引号(selectedIndex)</title>
</head>
<span>权力不私有,财产不公有</span>
<span>不能交给别人的三项基本权利:生命、财产、自由</span>
<span>人生下来的时候只是无知,但并不愚蠢,愚蠢是后来的教育造成的</span>
<body>
<select id="select">
<option>one</option>
<option>two</option>
<option>three</option>
</select>
<button onclick="get()">获取索引号</button>
<button onclick="reset()">重置索引号</button>
<script>
// 获取列表项(select)
var select = document.getElementById('select')
// 获取索引号
function get(){
console.log(`当前索引号:${select.selectedIndex}`)
}
// 重置索引号
function reset(){
let flag = select.selectedIndex //频繁使用封装一下(*^_^*)
if(flag == '0'){ // 重置索引值为0的列表项
flag = 999 //更改值为999
console.log(`重置后索引号:${flag}`)
console.log(`注意:重置不会改变原值,不信你看现在的值:${select.selectedIndex}`)
}
}
</script>
</body>
</html>
${'xxx','yyy'}
- 其实是这样的 ${}里边 依旧是js,外边也是js 什么场景使用最好呢
- 还记得字符串拼接吗没错,++++
- 例如: var a = 1;
- console.log(‘一共有’+a+‘个鸡蛋!’)
- 那么现在你只要
- console.log(
一共有${a}个鸡蛋!
)