选择选项值默认返回整数

Sru*_*Suk 7 html javascript

默认情况下,有没有办法从 Select Option as Integer 中获取值?

从这里选择

<select id="lesson_per_class" >
 <option value="">&nbsp;</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>
Run Code Online (Sandbox Code Playgroud)

当我尝试获取它们的值进行计算时,我发现它返回为 String 并且不能用于计算这里

var lesson_per_class = $('#lesson_per_class').val();
alert('value is ' + ( 10 + lesson_per_class )); 
// it give result as 10x instead of 1x 
Run Code Online (Sandbox Code Playgroud)

目前,我解决的方法是 parseInt(),但我需要知道,默认情况下是否必须将其作为 Integer 获取?

Glo*_*del 6

不,没有 -val()总是返回一个字符串。你必须使用parseInt()你自己已经发现的东西。

一种方法index()在这种情况下可能有效(因为第一个选项的索引为 0):

$('#lesson_per_class option:selected').index()
Run Code Online (Sandbox Code Playgroud)


mcc*_*inz 6

从规范中您可以看到该值是一​​个DOMString所以不,默认情况下您无法获得整数。

http://www.w3.org/TR/html5/forms.html#the-option-element

对于 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;
};
Run Code Online (Sandbox Code Playgroud)