点击错误循环的Jquery

时间:2017-01-20 14:15:34

标签: jquery

首先,我没有HTML控件。 我在某个地方的for循环中有错误,好像我只为一个id做它工作正常。

for (var i = 1; i < 73; i++) {
  $("#a" + i).click(function() {
    if ($("#a" + i).hasClass("green")) {
      $("#Q15v2_" + i).prop('checked', true);
    } else {
      $("#Q15v2_" + i).prop('checked', false);
    }
  });
}

1 个答案:

答案 0 :(得分:1)

试试这个让我知道:
检查此https://jsfiddle.net/shantaram/g1x7rh25/

$("p[id^=a").click(function() {   // paragraph id start with 'a'
    var len = $(this).prop('id').length;    // calculate id length
    var i = $(this).prop('id').substr(1,len);  // remove 'a' from id to get number
    if ($(this).hasClass("green")) {
        $("#Q15v2_" + i).prop('checked', true);
    } else {
        $("#Q15v2_" + i).prop('checked', false);
    }
});