简体   繁体   English

select元素的jQuery .val()返回文本

[英]jQuery .val() for select element returns text

Does jQuery .val() for select elements returns only text and not numbers? select元素的jQuery .val()只返回文本而不返回数字吗? You know there is a problem when you need to make a value comparison. 您知道在需要进行值比较时存在问题。

I know how to solve this with parseInt() or just comparing with string or by not using jQuery at all but what I don't know if this is a bug or the way jQuery just works. 我知道如何用parseInt()解决这个问题,或者只是与字符串比较或者根本不使用jQuery,但我不知道这是一个bug还是jQuery的工作方式。

From jQuery documentation > Value: Type: String or Number or Array A string of text, a number, or an array of strings corresponding to the value of each matched element to set as selected/checked. 从jQuery文档 > 值:类型:字符串或数字或数组一个文本字符串,一个数字或一个字符串数组,对应于要设置为选中/选中的每个匹配元素的值。

.val() Returns: String or Number or Array .val()返回:String或Number或Array

 // Put any number here 0 is the default selected value var comparison_value = 0; $('button').click(function () { $('div#typeof').text(typeof ($('select').val())); if ($('select').val() === comparison_value) { $('div#comparison').text('You just passed a test'); } else { $('div#comparison').text('You just failed a test'); } }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <select> <option value="0" selected>Select Something</option> <option value="1">One</option> <option value="2">Two</option> </select> <button>Gimme back my selection</button> <div id='typeof'></div> <div id='comparison'></div> 

You get what you've set in the value attribute of the select element, the value, which is "1" or "2", but as a string , input values are never anything else than strings (even if you may have accessors like valueAsNumber in HTML5). 你得到你在select元素的value属性中设置的值,即“1”或“2”,但作为一个字符串 ,输入值绝不是字符串(即使你可能有像HTML5中的valueAsNumber )。

If you want to get it as a number, use 如果您想将其作为数字,请使用

var selectedValue = +$('select').val();

If you want the index of the selected option, use 如果需要所选选项的索引,请使用

var selectedIndex = $('select')[0].selectedIndex;

Now, regarding the excerpt of the documentation you cite: it's about setting the value. 现在,关于您引用的文档的摘录:它是关于设置值。 If you pass a number, it will be converted to a string (and you'll get a string if you call .val() to get the value). 如果你传递一个数字,它将被转换为一个字符串(如果你调用.val()来获取值,你将获得一个字符串)。

What you are reading is the description of the value argument, not the returned value. 您正在阅读的是value参数的描述,而不是返回的值。

If we look at the source for .val() in the awesome jQuery Source Viewer we can see that there is a snippet to convert numbers to strings and joining arrays before setting them as a value. 如果我们在令人敬畏的jQuery Source Viewer中查看 .val()源代码,我们可以看到有一个片段可以将数字转换为字符串并在将它们设置为值之前连接数组。

// Treat null/undefined as ""; convert numbers to string
if (val == null) {
    val = "";
} else if (typeof val === "number") {
    val += "";
} else if (jQuery.isArray(val)) {
    val = jQuery.map(val, function (value) {
        return value == null ? "" : value + "";
    });
}

You did however seem to want return values and .val() is in theory able to return numbers if we trust the jQuery documentation which states Returns: String or Number or Array . 但是你确实想要返回值,而.val()理论上能够返回数字,如果我们信任jQuery文档,它说明了Returns: String or Number or Array The result is checked if the type is a string, if so \\r is stripped out and the string returned, else there is a null-check which might return the actual value or an empty string (which is commented to work for numbers or null-values). 如果类型是字符串,则检查结果,如果是,则删除\\r并返回字符串,否则存在可能返回实际值的空检查或空字符串(注释为对数字起作用或null) - 值)。

return typeof ret === "string" ?
    // handle most common string cases
    ret.replace(rreturn, "") :
    // handle cases where value is null/undef or number
        ret == null ? "" : ret;

The rreturn variable is declared in the global namespace as var rreturn = /\\r/g; rreturn变量在全局名称空间中声明为var rreturn = /\\r/g; so you can't find it with the source browser. 因此您无法使用源浏览器找到它。

So the real question here is can the DOM actually return numbers as values? 所以这里真正的问题是DOM实际上可以将数字作为值返回吗? The answer here seems to be "Yes, but only if you explicitly ask for it". 这里的答案似乎是“是的,但只有你明确要求它”。

Since HTML5 there is a new valueAsNumber -property on the HTMLInputElement interface that will return the value as a number is possible or NaN if not. 从HTML5开始,HTMLInputElement接口上有一个新的valueAsNumber -property ,它将返回值,因为数字是可能的,如果不是,则返回NaN。 This seems to only apply to HTMLInputElement though and is for example not available in the HTMLSelectElement interface . 这似乎仅适用于HTMLInputElement,例如在HTMLSelectElement接口中不可用。

I did a quick search through the latest jQuery sources (both latest nightly and the 1.11 release) and none of them use valueAsNumber today. 我快速搜索了最新的jQuery源代码(最新的每晚和1.11版本),今天没有人使用valueAsNumber Just speculating here, but this might have been added to the documentation before valueAsNumber was proposed just in case. 只是在这里进行推测,但是为了以防万一,在提出valueAsNumber之前,这可能已被添加到文档中。

So it seems that you are stuck with strings for the moment unless you yourself use valueAsNumber (and it should really just be used on <input type="number" /> or <input type="range" /> unless you add some manual validation). 因此,除非您自己使用valueAsNumber (并且它应该只用于<input type="number" /> or <input type="range" />除非您添加一些手册,否则您似乎暂时停留在字符串中)验证)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM