获取 span 标记内的选定选项值

Getting selected option value inside span tag

本文关键字:选项 span 获取      更新时间:2023-09-26

我需要获取位于span标签内的选定选项值。

<span id ="resolutionSpan">
    <select name="resolution" id="resolution">
    <option value="0" selected >0</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>     
    </select>
</span>

我试过了

var e = document.getElementById("resolution");
console.log( e.options[e.selectedIndex].text);

但这会返回一个空值。我需要先迭代跨度吗?

由于项目限制,我无法使用jquery。需要您在 JavaScript 中的注释

获取.options,然后.selectedIndex,然后.text。 喜欢这个:

var selected = document.getElementById('resolution').options[document.getElementById('resolution').selectedIndex].text
alert(selected);
<span id ="resolutionSpan">
    <select name="resolution" id="resolution">
    <option value="0" selected >0</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>     
    </select>
</span>

希望这有帮助!

我相信.text选择了标签。

如果需要所选项目的值,请使用 .value。

小提琴:http://jsfiddle.net/9wxqmLL1/

var e = document.getElementById("resolution");
console.log( e.options[e.selectedIndex].value);

你的代码实际上非常接近,只需将 .text 更改为 .value:

var e = document.getElementById("resolution");
console.log( e.options[e.selectedIndex].value);

除非您想获取选项的实际内容(在本例中为相同值但仍然如此)

var e = document.getElementById("resolution");
console.log( e.options[e.selectedIndex].innerHTML);