复选框点击不起作用,当我们把它放在列,这是可点击的

Check box click not working when we put it in column which is clickable

本文关键字:不起作用 我们 复选框      更新时间:2023-09-26

我创建了一个表格,并在每一列中添加了一个复选框

           <table class="bordered">
            <thead>
                <tr  style="cursor:pointer"  id="tableheading" >
                    <th>Name</th>
                       <th> 1</th>
                       <th> 2</th>
                </tr>
            </thead>
            <tbody>
                    <tr>
                        <td id="heading1">Sachith  sdf</td>
                           <td id="column11"> <input type="checkbox" disabled="disabled" id="checkbox11"/></td>
                           <td id="column12"> <input type="checkbox" disabled="disabled" id="checkbox12"/></td>
                    </tr>
            </tbody>
        </table>

,我使用Java脚本使该列可单击。当我选中复选框时,自动被选中和未选中。

                selectedIDs[1][1]="false";
                $("#column"+11).click(function() {
                    if(document.getElementById("checkbox"+11).checked){
                        $("#column"+11).removeClass('selected');
                        selectedIDs[1][1]="false";
                        document.getElementById("checkbox"+11).checked = false;
                    }else{
                        $("#column"+11).addClass('selected');
                        selectedIDs[1][1]="true";
                        document.getElementById("checkbox"+11).checked = true;
                    }
                });
                $("#column"+11).hover(
                    function(){
                        $("#column"+11).addClass('mouseover');
                    },
                    function(){
                        $("#column"+11).removeClass('mouseover');
                    }
                );

但现在的问题是,当我点击复选框什么都没有发生。

这是因为当您单击复选框时,默认行为将被触发,td单击处理程序也将被触发,这将恢复默认行为设置的值。

解决方案是不运行脚本,该脚本设置单击发生在checkbox元素中的选中值。

您可以通过为输入元素使用类而不是使用像

这样的id来简化事件处理程序注册。

$('#mysometable td.checkbox').on('click', function(e) {
  if (!$(e.target).is('input')) {
    $(this).find('input').prop('checked', function(i, checked) {
      return !checked;
    })
  }
})
#mysometable td {
  padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class="bordered" id="mysometable">
  <thead>
    <tr style="cursor:pointer" id="tableheading">
      <th>Name</th>
      <th>1</th>
      <th>2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td id="heading1">Sachith sdf</td>
      <td id="column11" class="checkbox">
        <input type="checkbox" id="checkbox11" />
      </td>
      <td id="column12" class="checkbox">
        <input type="checkbox" id="checkbox12"/>
      </td>
    </tr>
  </tbody>
</table>