1 回答

TA貢獻1853條經(jīng)驗 獲得超18個贊
一個文檔中不能有多個具有相同id
值的元素;您當前的標記使用id="language"
三個不同的元素。您至少需要更改其中兩個。
我想你問的是如何:
在兩個 s 中顯示當前選擇的選項的文本和值
span
,以及如果用戶更改選擇,如何更新您顯示的內(nèi)容。
如果您只想要選定的值,則可以使用元素value
的屬性select
。但是對于文本和值,您需要selectedIndex
屬性和options
集合:
function showTextAndValue(select, textSpan, valueSpan) {
const option = select.options[select.selectedIndex];
if (option) {
textSpan.textContent = option.text;
valueSpan.textContent = option.value;
} else {
// No option is selected
textSpan.textContent = "";
valueSpan.textContent = "";
}
}
在那個例子中,我讓它接受了select
和span
s 作為函數(shù)的參數(shù)。
您將在頁面加載時調(diào)用該函數(shù),然后在 的事件觸發(fā)時再次select
調(diào)用input
。
這是一個例子:
const select = document.getElementById("language-select");
const textSpan = document.getElementById("text-span");
const valueSpan = document.getElementById("value-span");
function showTextAndValue(select, textSpan, valueSpan) {
const option = select.options[select.selectedIndex];
if (option) {
textSpan.textContent = option.text;
valueSpan.textContent = option.value;
} else {
// No option is selected
textSpan.textContent = "";
valueSpan.textContent = "";
}
}
// Show on page load
showTextAndValue(select, textSpan, valueSpan);
// Hook the `input` event
select.addEventListener("input", () => {
// Update the contents of the elements
showTextAndValue(select, textSpan, valueSpan);
});
<label for="language">Choose a language:</label>
<select name="language" id="language-select" value="val1">
<option value="val1">English</option>
<option value="val2">German</option>
</select>
<p>You selected: <span id="text-span"></span></p> <!-- shall display either "English" or "German" -->
<p>You selected the following option: <span id="value-span"></span></p> <!-- shall display either "val1" or "val2" -->
<script src="./script.js"></script>
(請注意,我更改了所有三個id
。)
添加回答
舉報