2012-10-11 23 views
0

我有两个变量,如Question_typeAnswer_type在JavaScript中。如何在javascript中为hidden_​​field设置整数?

我有一个hidden_field没有价值,我想通过检查的Question_typeAnswer_type条件类似下面插入valuehidden_field

If Question_type == 'A' && Answer_type == 'B' { 
    hidden_field = 1; 
} else if Question_type == 'A' && Answer_type !== 'B' { 
    hidden_field = 2; 
} else if Question_type !== 'A' && Answer_type == 'B' { 
    hidden_field = 3; 
{ else if Question_type !== 'A' && Answer_type !== 'B' { 
    hidden_field = 4; 
} 

如何通过短格式或做这个概念JavaScript中的干净方法?任何JSFiddle示例都会更加流畅。 ')(' 如果要当且条件必须在里面:

+0

*“如何以简写的形式实现这个概念...”*您是在问如何缩短这段代码,或者如何设置字段的值? –

+1

缩短代码 – Vinay

回答

3

这里有一个选项,以缩短代码:

var isA = Question_type == 'A', 
    isB = Answer_type == 'B'; 

hidden_field = isA && isB ? 4 : 
       isA && !isB ? 3 : 
       !isA && isB ? 2 : 
           1; 

下面是另一个:

if (Question_type == 'A') 
    if (Answer_type == 'B') 
     hidden_field = 4; 
    else 
     hidden_field = 3; 
else 
    if (Answer_type == 'B') 
     hidden_field = 2; 
    else 
     hidden_field = 1; 
+0

非常感谢你 – Vinay

+0

不客气。 –

+1

@Vinay:我更新了答案*(顶部)*,因为我们确实不需要测试最后一个条件。如果前3个失败,那么最后一个将会通过,所以'0'永远不会被设置。 –

4

使用getElementById通过id来获取隐藏:

var hidden_field = document.getElementById('HiddenFieldId'); 
hidden_field.value = 1; 
1

修改后的代码。

if (Question_type == 'A' && Answer_type == 'B') { 
    $("#hidden_field").val(1); 
} else if (Question_type == 'A' && Answer_type !== 'B') { 
    $("#hidden_field").val( 2); 
} else if (Question_type !== 'A' && Answer_type == 'B') { 
    $("#hidden_field").val(3); 
{ else if (Question_type !== 'A' && Answer_type !== 'B') { 
     $("#hidden_field").val(4); 
} 
+2

jQuery!= Javascript – MalSu

+0

inside()是什么意思。我是新来的JavaScript。请定义? – Vinay

+0

好的MalSu。谢谢 – Vinay

-1

给隐藏字段一些ID,并设置它的值。

1

使用ternary operator可能有助于缩短代码:

if (Question_type == 'A') { 
    hidden_field.value = Answer_type == 'B' ? 1 : 2; 
} else { 
    hidden_field.value = Answer_type == 'B' ? 3 : 4; 
} 

check out this jsFiddle demo

相关问题