[英]Jquery .val() == ** adding multiple possible answers **
I achived this by doing the following, but as a newbie to javascript and jquery i want to know if there is any shorter way to add multiple possible values. 我通过执行以下操作实现了这一点,但作为javascript和jquery的新手,我想知道是否有任何更短的方法来添加多个可能的值。
if ($("input:first").val().toUpperCase() == "UNITED STATES" || $("input:first").val().toUpperCase() == "USA" || $("input:first").val().toUpperCase() == "AMERICA") {
$("#check").text("Correct!").show().fadeOut(5000);
return true;
Like 喜欢
if ($("input:first").val().toUpperCase() == ("UNITED STATES","USA","AMERICA")) {
$("#check").text("Correct!").show().fadeOut(5000);
return true;
by this only validates the last answers in this case AMERICA. 这样只能验证本案例中的最后答案AMERICA。
Using $.inArray() : 使用$ .inArray() :
if( $.inArray( $("input:first").val().toUpperCase(), [ "UNITED STATES", "USA", "AMERICA" ] ) > -1 ) { ...
Demo: http://jsfiddle.net/4ar2G/ 演示: http : //jsfiddle.net/4ar2G/
You can use an object where the keys are the required values and the in
operator: 您可以使用键是必需值的对象和
in
运算符:
var matches = { 'UNITED STATES': 1, 'USA': 1, 'AMERICA': 1 };
if ($("input:first").val().toUpperCase() in matches) {
...
}
In my experience this is actually surprisingly efficient - Javascript is rather good at looking up properties of objects, and it avoids a linear array scan so for larger arrays it's O(log n)
instead of O(n)
. 根据我的经验,这实际上是非常有效的 - Javascript相当擅长查找对象的属性,并且它避免了线性阵列扫描,因此对于较大的数组,它是
O(log n)
而不是O(n)
。
Don't use if you've messed with Object.prototype
, though! 不过,如果你已经搞乱了
Object.prototype
,请不要使用!
For the sake of balance, the equivalent non-jQuery way (because jQuery doesn't automatically mean better): 为了平衡,等效的非jQuery方式(因为jQuery不会自动意味着更好):
if(["UNITED STATES", "USA", "AMERICA"].indexOf($('input:first').val().toUpperCase()) > -1) {
$("#check").text("Correct!").show().fadeOut(5000);
return true;
}
Try this: 尝试这个:
if($.inArray($("input:first").val().toUpperCase(), ["UNITED STATES","USA","AMERICA"]) > -1){
$("#check").text("Correct!").show().fadeOut(5000);
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.