带变量的jQuery选择器循环
我得到了一个jSON ajax响应,如以下示例所示:带变量的jQuery选择器循环,jquery,variables,selector,Jquery,Variables,Selector,我得到了一个jSON ajax响应,如以下示例所示: ['PostA1'] =>1 ['PostA2'] =>1 ['PostA3'] =>2 ['PostB1'] =>1 ['PostB2'] =>3 ['PostB3'] =>0 ['PostB4'] =>2 ['Pre1'] =>1 ['Pre2'] =>2 ['Pre3'] =>1 ['Pre4'] =>3 ['Pre4'] =>3 PostA-x、PostB-x和
['PostA1'] =>1
['PostA2'] =>1
['PostA3'] =>2
['PostB1'] =>1
['PostB2'] =>3
['PostB3'] =>0
['PostB4'] =>2
['Pre1'] =>1
['Pre2'] =>2
['Pre3'] =>1
['Pre4'] =>3
['Pre4'] =>3
PostA-x、PostB-x和Pre data是指需要根据其值进行设置的单选按钮集。我可以通过编写一行代码来处理每个单独的代码,例如:
$("input[id='Pre1-" + data.Pre1 + "']").attr('checked','checked');
$("input[id='Pre1-" + data.Pre2 + "']").attr('checked','checked');
$("input[id='PostA1-" + data.PostA1+ "']").attr('checked','checked');
$("input[id='PostA2-" + data.PostA2 + "']").attr('checked','checked');
…等等…,但理想情况下,我希望能够循环遍历数据集,比如
i = 1;
$.each("--Aray which starts with PostA--" + i){
$("input:radio[id='PostA-" + data.PostA -- incrementer variable -- + "'].attr('checked',checked');
i++;
}
然后对三个数据集中的每一个重复这个循环…但是我真的被卡住了,因为首先我不太擅长jQuery选择器,其次我不知道如何在选择器中生成变量
希望这是有意义的!如果你们有任何关于如何做到这一点的建议(也许我完全走错了方向?!?),那将不胜感激
Dan为什么不迭代
数据
?您可以使用来执行此操作,并从每个键/值对构建当前元素的id:
$.each(data, function(key, value) {
$("#" + key + "-" + value).prop("checked", true);
});
您可以使用
for..in
循环对象
for (var key in data) {
// $("input[id='" + key + "-" + data[key]+ "']").prop('checked', true);
// below is better if select by id
$('#'+key+'-'+data[key]).prop('checked', true);
}