是,使用.options[]
和.selectedIndex
方法,您可以乾淨,悄悄地處理這個問題,像這樣:
HTML
<select name="select" id="select">
<option value="">...</option>
<option value="1">One</option>
<option value="2" selected="selected">Two</option>
</select>
的JavaScript
window.onload = function(){
var select = document.getElementById("select"), selected = select.value;
select.onchange = function(){
var val = select.options[select.selectedIndex].value;
if(val != selected) {
alert("Another value " + val + " was selected, which is not the same as the default value of " + selected);
} else {
alert("Same value as the default of " + selected + " was selected");
}
};
};
從JS中,你可以檢查並根據需要操作val
變量。
預選值總是一樣嗎?還是未知? –
@CrazyTrain它是未知的 – reformed
你可以修改選擇的渲染嗎?如果是這樣,你可以使用'data-'屬性給'select'引用原始索引,如'data-selected = 4'。然後在你的處理程序中比較if(select_elem.getAttribute(「data-selected」)!== select_elem.selectedIndex){...' –