答案 0 :(得分:3)
您会混淆属性和属性。更改属性是影响内存中对象的动态操作,它不会修改最初解析该元素的静态HTML。如果您想更改属性,则需要使用setAttribute()
或removeAttribute()
。
var select = document.body.querySelector('select');
// Get the element with the "selected" attribute
console.log("Element with 'selected' HTML attribute: " +
select.querySelector("[selected]").getAttribute("value"));
// Get the element with the "selected" value:
console.log("Element with value property of 'selected': " + select.value);
// Change the value property of the select
console.log("Changing value of select element to 'Rock'");
select.value = "Rock";
// Get the element with the "selected" attribute
console.log("Element with 'selected' HTML attribute: " +
select.querySelector("[selected]").getAttribute("value")); // Still Blues!
// Get the element with the "selected" value:
console.log("But, value of the select element is now: " + select.value); // Now Rock!
// Change which element has the selected attribute
console.log("Switching elment that has the 'selected' attribute...");
select.querySelector("[selected]").removeAttribute("selected");
select.querySelector("[value=Rock]").setAttribute("selected", "selected");
console.log("Element with 'selected' HTML attribute: " +
select.querySelector("[selected]").getAttribute("value"));
console.log(select.options[0])
console.log(select.options[1]);
<select>
<option value="Rock">Storm</option>
<option value="Blues" selected>Rain</option>
</select>
答案 1 :(得分:1)
要回答标题中的问题,您只需将所需选项设置为已选择。要获得当前<select>
值,应该查看select.value
:
let select = document.body.querySelector('select'),
newOption = new Option('Classic', 'Classic');
select.append(newOption);
select.options[2].selected = true;
console.log(select.value);
// Classic
<select>
<option value="Rock">Storm</option>
<option value="Blues" selected>Rain</option>
</select>
另请注意selected
属性仅标记默认选择,并且与selected
的{{1}}属性不同。该属性只是告诉浏览器是否应该在最初绘制DOM元素时将选项呈现为选中状态。
处理<option>
时,您需要检查<select multiple>
的{{1}}属性并将其映射到数组。例如:
.selectedOptions
<select>
.selectedOptions
是一个对象,其中包含选定的选项let select = document.body.querySelector('select'),
newOption = new Option('Classic', 'Classic');
select.append(newOption);
select.options[2].selected = true;
let values = [].slice.call(select.selectedOptions).map(a => a.value);
console.log(values)
// ["Blues","Classic"]
和原生方法,例如<select multiple>
<option value="Rock">Storm</option>
<option value="Blues" selected>Rain</option>
</select>
和length
。不包含备注选项组。