2 回答

TA貢獻1853條經驗 獲得超6個贊
人們只想聽一個選擇元素的變化。
因此,人們需要以某種方式識別這個特定的選擇元素,而不是它的每個選項元素。后者不需要具有name- 或id- 屬性,而是需要 -value屬性。
然后,我們會實現一個事件處理程序,該處理程序會讀取當前所選選項的值,并將該值寫入所需/相關的 html 元素。
還需要為前面提到的 select 元素提供事件偵聽/處理。
此外,我們希望在加載/渲染時將默認選定值與顯示元素同步。
筆記
出于安全原因,人們并不真正希望通過innerHTML...呈現文本值,在這種情況下,textContent寫訪問就可以很好地完成這項工作。
function handleMonthOptionChangeForRelatedDisplay(evt) {
const elementDisplay = document.querySelector('#month');
const elementSelect = evt.currentTarget;
if (elementDisplay && elementSelect) {
const elementSelect = evt.currentTarget;
const selectedIndex = elementSelect.selectedIndex;
elementDisplay.textContent = elementSelect[selectedIndex].value
}
}
function initMonthOptionChange() {
const elementSelect = document.querySelector('#month-options');
elementSelect.addEventListener('change', handleMonthOptionChangeForRelatedDisplay);
}
// window.onload = function () {
// handleMonthOptionChangeForRelatedDisplay({
// currentTarget: document.querySelector('#month-options')
// });
// initMonthOptionChange();
// }
handleMonthOptionChangeForRelatedDisplay({
currentTarget: document.querySelector('#month-options')
});
initMonthOptionChange();
<select name="plan_option" id="month-options">
<option value=""></option>
<option value="Ogni Mese">ogni mese</option>
<option value="Ogni due Mesi" selected>ogni due mesi</option>
</select>
<p id="month"></p>
如果OP必須呈現與選項元素的屬性不同的特定于選項的文本值,value仍然可以通過特定于選項的data屬性提供此信息的方法,以便使處理程序實現保持通用(沒有任何額外的和特定情況的比較邏輯)盡可能......
function displayBoundBillingFrequency(evt) {
const elementSelect = evt.currentTarget;
if (elementSelect) {
const selectedOption = elementSelect[elementSelect.selectedIndex];
// `this` equals the bound billing-frequency display-element.
this.textContent = (selectedOption.dataset.billingFrequency || '');
}
}
function mainInit() {
const planOptions = document.querySelector('#plan-options');
const frequencyDisplay = document.querySelector('#plan-billing-frequency');
if (planOptions && frequencyDisplay) {
const displayBillingFrequency = displayBoundBillingFrequency.bind(frequencyDisplay);
// synchronize display data initially.
displayBillingFrequency({
currentTarget: planOptions,
});
// initialize event listening/handling
planOptions.addEventListener('change', displayBillingFrequency);
}
}
mainInit();
<select name="plan_option" id="plan-options">
<option value=""></option>
<option value="541758" data-billing-frequency="ogni mese" selected>First Option</option>
<option value="752649" data-billing-frequency="ogni due mesi">Second Option</option>
<option value="invalid">Invalid Option</option>
</select>
<p id="plan-billing-frequency"></p>

TA貢獻2003條經驗 獲得超2個贊
您應該檢查HTMLElement:change 事件
var planSelectElem = document.getElementById("plan_select"); // <select id="plan_option_select"></select>
planSelectElem.onchange = month_freq;
// OR
planSelectElem.addEventListener("change", month_freq);
添加回答
舉報