Javascript 如何使用条件运算符分配ID?
我在一个页面上有四个表单,我想为所有表单分配一个密码验证函数。我想获取当前密码字段的ID并进行进一步验证 我获取当前输入密码字段的ID,如下所示:Javascript 如何使用条件运算符分配ID?,javascript,jquery,if-statement,conditional-operator,Javascript,Jquery,If Statement,Conditional Operator,我在一个页面上有四个表单,我想为所有表单分配一个密码验证函数。我想获取当前密码字段的ID并进行进一步验证 我获取当前输入密码字段的ID,如下所示: var id = $(this).attr('id'); 现在我想使用三元if来检查ID并为变量赋值。例如: var a if id==1 a= "a"; else if id==2 a= "b"; else if id==3 a = "c" else if id==4 a = "d" 感谢您的帮助。三元运算符您指的是: var
var id = $(this).attr('id');
现在我想使用三元if
来检查ID并为变量赋值。例如:
var a
if id==1
a= "a";
else if id==2
a= "b";
else if id==3
a = "c"
else if id==4
a = "d"
感谢您的帮助。三元运算符您指的是:
var value = (condition)
? 'result if condition is true'
: 'result if condition is false';
我认为使用对象或开关应该更清楚
例如:
var values = {
1: 'a',
2: 'b',
3: 'c',
4: 'd',
}
var id = $(this).attr('id');
var result = values[ id ] ? values[ id ] : 'default';
// Alternative syntax using the || operator
var result = values[ id ] || 'default';
使用开关
station
var id = $(this).attr('id');
var result = getValue( id );
function getValue( id ) {
switch( id ) {
case 1: return 'a';
case 2: return 'b';
default: return 'default value';
}
}
如果确实要使用三元运算符:
var id = $(this).attr('id');
var a = (id==1) ? "a" : (id==2) ? "b" : (id==3) ? "c" : (id==4) ? "d" : undefined;
虽然如果您需要使用开关对同一变量进行多个此类比较
将是一个更好的选择:
var a;
switch ($(this).attr('id')) {
case 1:
a = "a";
break;
case 2:
a = "b";
break;
case 3:
a = "c";
break;
case 4:
a = "d";
break;
}
如果id的值实际上是连续的数字,您甚至可以使用数组:
var id = $(this).attr('id');
var a = [, "a", "b", "c", "d"][+id];
var某物=[“a”、“b”、“c”、“ddd”];
$(“表格”)。关于(“提交”,职能部门(evt){
evt.preventDefault();
var$password=$(this).find(“[name='password']”);
var bla=something[+$password[0].id-1];//-1,因为它基于索引(0)
控制台日志(bla)
});代码>
那么,您是否尝试过使用条件运算符?请向我们展示您的尝试。var a=“abcd”[id-1]
为什么不直接使用对象<代码>常量obj={1:“a”,2:“b”,3:“c”,4:“d”};var a=对象[id]对象更高效(关于O(1)
access),可以在运行时修改绑定,并生成更干净的代码。那就用物品吧。非常感谢大家:)帮了我很多忙