问题
This is a simple question but I cannot find any reference so here it goes.
Assume I have a select element:
<select id="sel">
<option value="1">1</option>
<option value="2">2</option>
</select>
Now I want to get its selected option's value
. Most often I see this kind of snippet being used:
var sel = document.getElementById('sel');
console.log( sel.options[sel.selectedIndex].value ); //1
Which works great. However, I've found out that select
elements also have a value property:
console.log( sel.value ); //1
See fiddle with both examples.
The second form is not only much simpler, it also works all the way back to IE6 (yes, I did actually test on that, here's the IE6 friendly version).
Is there a reason why the first approach is so much more widely accepted? Is there some incompatibility or corner-case issue with the second approach?
ps. My "most used approach" thesis was based mostly on personal experience, but as for reference, the two most upvoted answers in Get selected value in dropdown list using JavaScript? uses the first approach.
回答1:
The MDN page tells us
options
nsIDOMHTMLOptionsCollection The set of elements contained by this element. Read only.
selectedIndex
long The index of the first selected element.
value
DOMString The value of this form control, that is, of the first selected option.
However it also says
selectedOptions
Unimplemented (see bug 596681) HTMLCollection The set of options that are selected. HTML5
Therefore, if you want to have a multi-select but general compatibility, you'll have to loop over options
, but if you have a single-select, sel.options[sel.selectedIndex].value
and sel.value
are equivalent, but the prior is "more similar" to the form a loop for a multi-select would take.
回答2:
The first option is widely accepted only because its more well known. The 2nd option is perfectly fine.
Have you verified that it works on Navigator 4?
来源:https://stackoverflow.com/questions/15661298/do-select-elements-have-a-standard-value-property