如何使用jquery在表格单元格内设置复选框?

时间:2018-01-27 14:43:05

标签: jquery asp.net

我正在尝试在给定索引的每一行的第一个单元格内设置一个复选框。 如何访问该复选框? 到目前为止我已尝试过以下内容:

function checkLocationTable (colindexes,tablename) {
    var table = document.getElementById(tablename);
    for (var i = 0, row; row = table.rows[i]; i++) {
        if (colindexes.includes(i)) {
            $(this).find("td:eq(0) .checkbox").prop("checked", true);
        }
    }
}

colindexes是一个整数数组,例如[1, 2, 3]

我也尝试过:

function checkLocationTable(colindexes, tablename) {
    $("#" + tablename + " tr").each(function(index) {
        if ($.inArray(colindexes, index)) {
            $(this).find("td:eq(0) > checkbox").attr("checked", true);
        }
    });
}

第二个例子甚至没有进入内部函数。

3 个答案:

答案 0 :(得分:1)

我认为您需要对行对象进行选择而不是:

function checkLocationTable (colindexes,tablename){
            var table = document.getElementById(tablename);
            for (var i = 0, row; row = table.rows[i]; i++) {
                if(colindexes.includes(i))
                {

                    $(row).find("td:first input:checkbox").prop("checked",true);

                }
            }
        }

答案 1 :(得分:1)

根据您的上一次尝试。你的代码几乎是正确的。 $ .inArray中参数的顺序应该是Index,colindexes,而不是colindexes,index。此外,我添加了>= 0,因为当找不到元素时,inArray返回-1。

checkLocationTable([0, 2], 'table1')

function checkLocationTable(colindexes, tablename) {
  $("#" + tablename + " tr").each(function(index) {
    if ($.inArray(index, colindexes) >= 0) {
      $(this).find("td:eq(0) > input[type='checkbox']").attr("checked", true);
    }
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table1">
  <tr>
    <td>
      <input type="checkbox" />
    </td>
    <td>
      <input type="checkbox" />
    </td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" />
    </td>
    <td>
      <input type="checkbox" />
    </td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" />
    </td>
    <td>
      <input type="checkbox" />
    </td>
  </tr>
</table>

Sizzle表达式以input[type='checkbox']而非checkbox结尾。

答案 2 :(得分:0)

你把“.checkbox”放在你的javascript函数中,找到带有类名的元素复选框,这可能是我的问题,试试这个:

function checkLocationTable (colindexes,tablename){
        var table = document.getElementById(tablename);
        for (var i = 0, row; row = table.rows[i]; i++) {
            if(colindexes.includes(i))
            {

                $(this).find("td:eq(0) checkbox").prop("checked",true);

            }
        }
    }

在你的Jquery中,inArray被赋予错误,应该是,

function checkLocationTable(colindexes,tablename)
{
     $("#"+tablename+" tr").each(function(index){ 
       if($.inArray(index,colindexes))
       {
          $(this).find("td:eq(0) > checkbox").prop("checked",true);
       }
  });
}

希望这有帮助!