jQuery选择器循环使用变量变量

时间:2012-08-27 10:23:56

标签: 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和Pre数据是指需要根据其值设置的单选按钮组。我可以通过编写一行代码来处理每个单独的代码,例如:

$("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选择器上并不是那么出色,其次我不知道如何在选择器中创建变量变量。

希望这是有道理的!如果你们对如何做到这一点有任何建议(也许我会以完全错误的方式进行这种方式?!?!?)那么我们将非常感激。

2 个答案:

答案 0 :(得分:1)

您可以使用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);
}

答案 1 :(得分:0)

为什么不反复遍历data?您可以使用$.each()来执行此操作,并从每个键/值对构建当前元素的ID:

$.each(data, function(key, value) {
    $("#" + key + "-" + value).prop("checked", true);
});