javascript 选择选项值默认返回整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31434805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select Option Value return Integer by default
提问by Sruit A.Suk
Is it has any way to get value from Select Option as Integer by default ?
默认情况下,有没有办法从 Select Option as Integer 中获取值?
from select here
从这里选择
<select id="lesson_per_class" >
<option value=""> </option>
<option value="1">1 Lesson</option>
<option value="2">2 Lessons</option>
<option value="3">3 Lessons</option>
<option value="4">4 Lessons</option>
</select>
When I tried to get their value to calculate, I found that it return as String and can't use to calculate here
当我尝试获取它们的值进行计算时,我发现它返回为 String 并且不能用于计算这里
var lesson_per_class = $('#lesson_per_class').val();
alert('value is ' + ( 10 + lesson_per_class ));
// it give result as 10x instead of 1x
currently, the way I solved is parseInt(), but I need to know, is it has anyway to get it as Integer by default?
目前,我解决的方法是 parseInt(),但我需要知道,它是否必须默认将其作为 Integer 获取?
回答by mccainz
From the spec you can see the value is a DOMStringso no, you cannot get an integer by default.
从规范中您可以看到该值是一个DOMString所以不,默认情况下您无法获得整数。
http://www.w3.org/TR/html5/forms.html#the-option-element
http://www.w3.org/TR/html5/forms.html#the-option-element
For Java and ECMAScript, DOMString is bound to the String type because both languages also use UTF-16 as their encoding.
对于 Java 和 ECMAScript,DOMString 绑定到 String 类型,因为这两种语言也使用 UTF-16 作为它们的编码。
[NamedConstructor=Option(optional DOMString text = "", optional DOMString value, optional boolean defaultSelected = false, optional boolean selected = false)]
interface HTMLOptionElement : HTMLElement {
attribute boolean disabled;
readonly attribute HTMLFormElement? form;
attribute DOMString label;
attribute boolean defaultSelected;
attribute boolean selected;
attribute DOMString value;
attribute DOMString text;
readonly attribute long index;
};
回答by Glorfindel
No, there isn't - val()
always returns a string. You have to use parseInt()
as you already found out yourself.
不,没有 -val()
总是返回一个字符串。你必须使用,parseInt()
因为你已经发现自己。
There isan index()
method, which might work in this case (because the first option has index 0):
这里是一个index()
方法,它可能会在这种情况下工作(因为第一个选项具有索引0):
$('#lesson_per_class option:selected').index()