单击行上的任意位置以选中复选框并突出显示它


click anywhere on the row to check the checkbox and highlight it?

我有一个脚本,它将从mysql DB获取结果,并以整洁的表格格式显示包含所有结果的复选框。我想让它像,单击行上的任意位置以触发复选框并突出显示整行。一次可选择多行。

我已经尝试了JS方法进行onlclick和getElementById功能,并使用:checked在CSS中使用。到目前为止没有任何进展。

<table id="tab-1">
    <thead>
        <tr>
            <th scope="col">Select</th>
            <th scope="col">ID</th>
            <th scope="col">A</th>
            <th scope="col">B</th>
            <th scope="col">C</th>
            <th scope="col">D</th>
            <th scope="col">E</th>
            <th scope="col">E</th>
            <th scope="col">F</th>
            <th scope="col">G</th>
            <th scope="col">H</th>
            <th scope="col">I</th>
            <th scope="col">J</th>
            <th scope="col">k</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><input type="checkbox" name="checkbox[]" id="checkbox[]" value="<?php echo $row['ID']; ?>"  /></td>
            <td><?php echo $row['ID']; ?></td>
            <td><?php echo $row['A']; ?></td>
            <td><?php echo $row['B']; ?></td>
            <td><?php echo $row['D']; ?></td>
            <td><?php echo $row['E']; ?></td>
            <td><?php echo $row['F']; ?></td>
            <td><?php echo $row['G']; ?></td>
            <td><?php echo $row['H']; ?></td>
            <td><?php echo $row['I']; ?></td>
            <td><?php echo $row['J']; ?></td>
            <td><?php echo $row['K']; ?></td>
            <td><?php echo $row['L']; ?></td>
            <td><?php echo $row['M']; ?></td>
        </tr>
    </tbody>
<table>

如果可以使用 jquery,可以尝试

$(document).on('click','tr',function(){
 $(this).find('input[type="checkbox"]').prop('checked',true);
 $(this).css('background','yellow'); // or anything else for highlighting purpose
});

根据注释更新了 JSFiddle

例如,使用 jQuery:

$('#table').on('click', 'tr', function() {
    $(this).find('td:first :checkbox').trigger('click');
})
.on('click', ':checkbox', function(e) {
    e.stopPropagation();
    $(this).closest('tr').toggleClass('selected', this.checked);
});

演示:http://jsfiddle.net/3E4Lk/2/

您可以使用

classList.toggle 切换行上的活动类,并使用 !ele.checked 切换复选框的复选框。

.CSS

tr.active {
   background:rgba(0,255,0,0.35);
}

爪哇语

function rowClicked(){
   var inputs = this.getElementsByTagName("input");
   var checkboxes = [].filter.call(inputs,function(input){
      return input.type == "checkbox" && input.name == "checkbox[]";
   });
   this.classList.toggle("active");       
   if(checkboxes[0]) checkboxes[0].checked = this.classList.contains("active")
}
window.addEventListener("load",function(){
   var table = document.getElementById("tab-1");
   var rows = table.getElementsByTagName("tbody")[0].getElementsByTagName("tr");
   for(var i=0; i<rows.length; i++){
      rows[i].addEventListener("click",rowClicked);
   }
});

JSFiddle