[英]Conditional checkbox checked jquery
I'm trying to add a value of checked for specific elements. 我正在尝试为特定元素添加一个checked值。
function renderList() {
$.getJSON("/search", function(response) {
$.each(response, function(index, value) {
$('ul').append($('<li>')
.append(value.task)
.append('<input type="checkbox"/>')
.append('<span>x</span>'))
})
});
}
I would like to add a conditional statement for the checkbox value of "checked" 我想为“ checked”复选框的值添加一个条件语句
When I add .attr('checked', true)
, it is added to the li and not the checkbox. 当我添加
.attr('checked', true)
,它被添加到li中而不是复选框中。
You can do something like this: 您可以执行以下操作:
function renderList() {
$.getJSON("/search", function(response) {
$.each(response, function(index, value) {
var checkedString = '';
if( value == 'something'){
checkedString = 'checked="checked"';
}
$('ul').append($('<li>')
.append(value.task)
.append('<input type="checkbox" ' + checkedString + '/>')
.append('<span>x</span>'))
})
});
you can try 你可以试试
$.each(response, function(index, value) {
var valueChecked = (value.checked)? ' checked ': '';
$('ul').append($('<li>' + value.task +
'<input type="checkbox" '+ valueChecked +' />' +
'</li>')
valueChecked get ' checked ' value if value.checked (the property choosed by you) is true; 如果value.checked(由您选择的属性)为true,则valueChecked获得“已检查”的值;否则为false。
there's no need to write .append('li') .... .append(' 无需编写.append('li').... .append('
Hope this help you! 希望这对您有所帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.