一、selectoptions
在HTML中,經常需要在表單中添加下拉框,而標籤就是用來定義下拉框的。而標籤需要配合標籤使用,而selectoptions數組就是用來獲取一個標籤中包含的所有標籤的集合。
var sel = document.getElementById("mySelect");
var options = sel.options;
for(var i=0; i<options.length; i++) {
console.log(options[i].value);
}
二、selectoption屬性
每個標籤都有相關屬性,比如value、label、selected等等。而這些屬性可以通過selectoption對象的屬性來獲取。使用option對象的value來獲取選中的選項的值。
var sel = document.getElementById("mySelect");
var selectedOption = sel.options[sel.selectedIndex];
console.log(selectedOption.value);
三、selectoption1-3
在設置標籤的多個標籤時,可以使用selectoptions數組中的下標來獲取每個標籤對應的selectoption對象。
var sel = document.getElementById("mySelect");
var option1 = sel.options[0];
var option2 = sel.options[1];
var option3 = sel.options[2];
console.log(option1.value, option2.label, option3.selected);
四、獲取select的option值
可以通過selectoptions數組來獲取標籤中每個標籤的值。
var sel = document.getElementById("mySelect");
var options = sel.options;
for(var i=0; i<options.length; i++) {
console.log(options[i].value);
}
五、option, select, select選中觸發事件
在使用標籤時,我們可能需要通過option或select來觸發一些事件,比如當選項改變時觸發change事件。
var sel = document.getElementById("mySelect");
sel.addEventListener("change", function() {
console.log(sel.value);
});
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/201014.html
微信掃一掃
支付寶掃一掃