设置下拉框属性
books = document.getElementById('books');
console.log(books);
// 设置第几个被选中
books.selectedIndex = 1;
console.log(books.selectedIndex) // 0
Select 对象方法
添加和删除下拉框选项
<select name="books-option" id="books">
<option value="1">Python</option>
<option id="x" value="2">JavaScript</option>
<option value="3">Java</option>
</select>
</form>
<script>
books = document.getElementById('books');
console.log(books);
var option=document.createElement("option");
option.text="c++";
// add()
books.add(option)
</script>
add不传第二个参数,默认添加到最后
第二个参数,可以指定添加位置, 比如添加到第一个后面
books = document.getElementById('books');
console.log(books);
var option=document.createElement("option");
option.text="c++";
books.add(option, '1')
如果添加到第一个位置,第二个参数传 0
books.add(option, 0)
remove() 移除一个选项
selectObject.remove(index)
参数index是下拉框的索引位置
<div id="demo">
<p>select 下拉框</p>
<select name="books-option" id="books">
<option value="1">Python</option>
<option id="x" value="2">JavaScript</option>
<option value="3">Java</option>
</select>
</form>
<script>
books = document.getElementById('books');
console.log(books);
books.remove(1);
</script>
HTMLOptionsCollection()对象
options 属性返回HTMLOptionsCollection()对象,选项集合
HTMLOptionsCollection()属性
<option value="1">Python</option>
<option value="2">JavaScript</option>
<option value="3">Java</option>
</select>
</form>
<script>
books = document.getElementById('books');
console.log(books);
// options 获取全部选项
console.log(books.options) // HTMLOptionsCollection(3) [option, option, option, selectedIndex: 0]
// length 属性
console.log(books.length); // 3
// selectedIndex 被选中索引
console.log(books.selectedIndex ); //0
// 索引取值
console.log(books.options[0]);
console.log(books.options.item(0));
</script>