选择元素是否具有标准值属性? [英] Do select elements have a standard value property?

查看:111
本文介绍了选择元素是否具有标准值属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的问题,但我找不到任何参考,所以这里。



假设我有一个选择元素:

 < select id =sel> 
< option value =1> 1< / option>
< option value =2> 2< / option>
< / select>

现在我想要获取其选定的选项的。大多数情况下,我看到这样的片段被使用:

  var sel = document.getElementById('sel'); 
console.log(sel.options [sel.selectedIndex] .value); // 1

哪个工作很好。但是,我发现选择元素也有一个值属性:

  console.log(sel.value); // 1 

请参阅 小提琴 两个例子。



第二种形式不仅简单得多,它也可以全部工作回到IE6的方法(是的,我实际上测试了,这里是 IE6友好版本 )。



是否有理由为什么第一种方法被广泛接受?第二种方法是否有不兼容性或角落问题?



ps。我的最常用的方法论文主要基于个人经验,但作为参考,在使用JavaScript在下拉列表中获取所选值使用第一种方法。

解决方案

MDN网页 告诉我们


选项 nsIDOMHTMLOptionsCollection 元素包含这个元素。



selectedIndex long 第一个选定元素的索引。 p>

value DOMString 此表单控件的值,即第一个选定的选项


但是它也说


selectedOptions 未实现(请参阅错误596681) HTMLCollection 所选的一组选项。 HTML5


因此,如果您想要具有多选但一般的兼容性,则必须循环选项,但如果您有单选, sel.options [sel.selectedIndex] .value sel.value 是等效的,但是先前的是与更多选择的循环的形式更相似。


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.

解决方案

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.

这篇关于选择元素是否具有标准值属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆