jQuery .val()对于选择元素只返回文本而不是数字吗?
当您需要进行值比较时,就会出现问题。
我知道如何通过
从jQuery文档中可以看到:> 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.
我知道如何通过
parseInt()
解决这个问题,或者只需将其与字符串进行比较,或者根本不使用jQuery,但我不知道这是否是一个错误,还是jQuery的工作方式。从jQuery文档中可以看到:
.val()返回:字符串、数字或数组
// 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>
val()
方法的引用。 - A. Wolff