[英]Check Checkbox in jquery
這是我目前的代碼。 我想要完成的是如下。
如果json[i].enabled
為true,我需要選中相應的復選框。 如果沒有,請將其留空。
function createTable(json) {
var element = "";
var i;
for (i = 0; i < json.length; i++) {
element = element
+ '<tr><td><input type= "checkbox"/></td><td>'
+ json[i].a_id + '</td><td>' + json[i].name + '</td><td>'+ json[i].enabled
+ '</td></tr>';
if(json[i].enabled== "TRUE"){
$('checkbox').prop('checked', true);
}
}
//Had forgotten to add this before.
element = element + '</tbody>';
$('#dataTable > tbody').remove();
$("#dataTable").append(element);
}
我嘗試通過包括以下if條件但它失敗了。
if(json[i].enabled== "TRUE"){
$('checkbox').prop('checked', true);
}
那么,我該怎么做呢? 如何訪問循環中的特定復選框?
謝謝!
尚未在DOM中創建checbox元素。 所以你必須把html放在第一位。 然后用
input[type="checkbox"]
匹配實際的復選框元素。 最后,您可能希望僅使用此選擇器獲取最后一個復選框(在表的最后一行中):
mytable tbody tr:最后輸入[type =“checkbox”]
所以你有以下代碼:
function createTable(json) {
var i;
for (i = 0; i < json.length; i++) {
// construct the html
element = '<tr><td><input type= "checkbox"/></td><td>'
+ json[i].a_id + '</td><td>' + json[i].name + '</td><td>'+ json[i].enabled
+ '</td></tr>';
// put the html in the page
$('#mytable tbody').append(element);
if(json[i].enabled== "TRUE"){
// get the last inserted line in the table and check the checkbox
$('#mytable tbody tr:last input[type="checkbox"]').prop('checked', true);
}
}
}
$('input[type="checkbox"]').prop('checked', true);
完整的例子:
var $table=jQuery('<table></table>');
for (i = 0; i < json.length; i++) {
var $tr=jQuery(
'<tr><td><input type= "checkbox"/></td><td>'
+ json[i].a_id + '</td><td>' + json[i].name + '</td><td>'+ json[i].enabled
+ '</td></tr>');
if(json[i].enabled== "TRUE"){
$tr.find('input["checkbox"]').prop('checked', true);
}
$table.append($tr);
}
$jQuery('body').append($table);
使用字符串連接和三元運算符:
'<tr><td><input type="checkbox"' + ( json[i].enabled== "TRUE" ? ' checked' : '' ) + '/></td><td>'
嘗試這個:
$('input[type="checkbox"]:eq(i)').prop('checked', true);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.