2016-04-20 56 views
2

我有这样的代码:真假条件直列

<input type='checkbox'> 

我要让有条件使用jQuery,例如,如果data[1].conditiontrue,然后将其选中,如果没有的话不。

可能是这样的:

<input type='checkbox' + if data[1].condition is false, unchecked + "'> 

<input type='checkbox' + if data[1].condition is true, checked + "'> 

有没有一种方法来设置它内联?例如:

<input type='checkbox' + data[1].condition | checked + "'> 
+0

你是否使用任何JS库或JS? – user1027620

+1

你使用了什么样的模板语言?你不能只用HTML来做到这一点。 – Steve

+0

我很困惑...你想避免JS或jQuery? –

回答

1

有没有真正的方法来做到这一点内联。

使用jQuery ...

if(data[1].condition === false){ 
    $('input').removeAttr('checked'); 
} else { 
    $('input').prop('checked', true); 
} 
1

答案很简单:不!

你不能使用HTML和JS来使用它。但是,如果您使用像EJS这样的模板库,则可以根据需要以内联方式完成。

<input type="checkbox" <%= data[1].condition ? 'checked' : '' %> /> 

另一种选择是使用JS/jQuery来设置使用脚本的属性,如上面Brad所做的那样。