通过比较值来使复选框处于选中状态

问题描述

|| 我有以下复选框列表,该列表是从服务器以HTML格式生成的。我也有一个如下的Javascript数组。 我想遍历数组,并针对每个复选框检查每个值。如果有匹配项,请选中该复选框。 我正在使用jQuery 1.4。
<script>
//this array is a result of an Ajax call
var arrMonth = [ \"November\",\"October\",\"December\"];

//Loop through the array and check each element against the check Box list
//if found,make the checkBox checked
jQuery.each(arrMonth,function( intIndex,objValue) {

        // script to check against the each checBox in the table ctl00_ContentPlaceHolder1_cbStudentTypeEdit

});

</script>
生成的复选框列表:
<table cellspacing=\"10\" cellpadding=\"20\" border=\"0\" id=
  \"ctl00_ContentPlaceHolder1_cbStudentTypeEdit\">
    <tbody>
      <tr>
        <td><span idkey=\"1\"><input type=\"checkBox\" tabindex=\"3\" name=
        \"ctl00$ContentPlaceHolder1$cbStudentTypeEdit$0\" id=
        \"ctl00_ContentPlaceHolder1_cbStudentTypeEdit_0\" />
        <label for=\"ctl00_ContentPlaceHolder1_cbStudentTypeEdit_0\">October</label></span></td>

        <td><span idkey=\"3\"><input type=\"checkBox\" tabindex=\"3\" name=
        \"ctl00$ContentPlaceHolder1$cbStudentTypeEdit$2\" id=
        \"ctl00_ContentPlaceHolder1_cbStudentTypeEdit_2\" />
        <label for=\"ctl00_ContentPlaceHolder1_cbStudentTypeEdit_2\">November</label></span></td>
      </tr>

      <tr>
        <td><span idkey=\"2\"><input type=\"checkBox\" tabindex=\"3\" name=
        \"ctl00$ContentPlaceHolder1$cbStudentTypeEdit$1\" id=
        \"ctl00_ContentPlaceHolder1_cbStudentTypeEdit_1\" />
        <label for=\"ctl00_ContentPlaceHolder1_cbStudentTypeEdit_1\">December</label></span></td>

        <td><span idkey=\"4\"><input type=\"checkBox\" tabindex=\"3\" name=
        \"ctl00$ContentPlaceHolder1$cbStudentTypeEdit$3\" id=
        \"ctl00_ContentPlaceHolder1_cbStudentTypeEdit_3\" />
        <label for=\"ctl00_ContentPlaceHolder1_cbStudentTypeEdit_3\">January</label></span></td>
      </tr>
    </tbody>
  </table>
谢谢。     

解决方法

        
// jQuery wrapper
(function($){

    // document-ready wrapper
    $(function(){

        var arrMonth = [ \"November\",\"October\",\"December\"];

        //Loop through the array and check each element against the check box list
        //if found,make the checkbox checked
        $.each(arrMonth,function( intIndex,objValue) {

            $(\"label:contains(\'\" + objValue + \"\')\").each(function(){
                // jquery 1.5 and earlier: use attr instead of prop
                $(\"#\" + $(this).attr(\"for\")).prop(\"checked\",true);
            });
        });

    });

})(jQuery);
工作演示:http://jsfiddle.net/roberkules/3QjYk/