我正在尝试根据通过 ajax 调用接收到的 json 数据将 css 类添加到复选框标签。除了在列表的值已经可用时将 css 类应用于复选框标签之外,我可以阅读数据并使用数据执行必要的任务。我错过了什么?
当 ajax 成功时,我调用 studatapopulate(1,app);
以下是我的 js
function studatapopulate(id, data) {
var ref = data[id].ref;
var exam = data[id].exam;
var tutes = "";
jQuery.each(data[id].tutedata, function (index, value) {
tutes += '<li>'+value.subj+'</li>';
tutes += '<ul>';
var i;
for (i = 1; i < 21; ++i) {
tutes += '<li><label class="tutebtn" for="'+id+'_'+value.id+'_'+i+'"><input type="checkbox" id="'+id+'_'+value.id+'_'+i+'" data-subj="'+value.id+'" value="'+i+'"';
jQuery.each(value.issuedtutes, function (indexa, valuae) {
if (valuae == i) {
jQuery(this).closest('label').addClass('tutegot');
tutes += ' checked="checked" disabled="disabled"';
}
});
tutes += '/> '+i+'</label></li>';
}
tutes += '</ul>';
});
jQuery("#tutes_"+id).append('<ul>'+tutes+'</ul>');
}
我试过 parent
,parents
但没有成功
issuedtutes
的示例数据 => ["5","9","16"]
checked="checked"disabled="disabled"
对上述内容正常工作,使第 5、9 和 16 项选中并禁用。
最佳答案
解决方案:
在添加元素之前不要选择最近的标签。
在将 html 元素附加到 tute_[id] 后,只需添加 tutegot 类即可。
这可能不是最佳解决方案。但这有效。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
HI
<ul id="tutes_1">
</ul>
<script>
function studatapopulate(id, data) {
var ref = data[id].ref;
var exam = data[id].exam;
var tutes = "";
jQuery.each(data[id].tutedata, function (index, value) {
tutes += '<li>'+value.subj+'</li>';
tutes += '<ul>';
var i;
for (i = 1; i < 21; ++i) {
tutes += '<li><label class="tutebtn" for="'+id+'_'+value.id+'_'+i+'"><input type="checkbox" id="'+id+'_'+value.id+'_'+i+'" data-subj="'+value.id+'" value="'+i+'"';
jQuery.each(value.issuedtutes, function (indexa, valuae) {
if (valuae == i) {
tutes += ' checked="checked" disabled="disabled"';
}
});
tutes += '/> '+i+'</label></li>';
}
tutes += '</ul>';
});
jQuery("#tutes_"+id).append('<ul>'+tutes+'</ul>');
$("input:checkbox:checked").parent().addClass("tutegot")
}
var a = {
1: {
ref: 123,
exam: 123,
tutedata: [
{
id: 1001,
subj: 'a',
issuedtutes: [
"5", "9", "16"
],
},
{
id: 1002,
subj: 'b',
issuedtutes: [
"5", "9", "16"
],
}
]
}
};
studatapopulate (1, a);
</script>
</body>
</html>
编辑 1: 代码按照@Carsten Løvbo Andersen 的建议进行了优化。
关于javascript - 基于 Json 数据通过 JavaScript 函数添加类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57249664/