3

大家好?你能帮忙吗?我在 HTML 中有这个表格。我想要实现的是,当我单击该行时,复选框将被选中并且该行将被突出显示。是否可以隐藏复选框列?

<table border="1" id="estTable">
<thead>
    <tr>
        <th></th>
        <th>Name</th>
        <th>Age</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td><input type="checkbox"></td>
        <td>Chris</td>
        <td>10</td>
    </tr>
    <tr>
        <td><input type="checkbox"></td>
        <td>Cass</td>
        <td>15</td>
    </tr>
    <tr>
        <td><input type="checkbox"></td>
        <td>Aldrin</td>
        <td>16</td>
    </tr>

</tbody>

</table>
<input type="button" value="Edit" id="editbtn"/>

<div id="out"></div>

我有这个 javascript 来获取所选行的值。我希望一次打印一行。

 $('#editbtn').click(function(){

    $('#estTable tr').filter(':has(:checkbox:checked)').find('td').each(function() {
         $('#out').append("<p>"+$(this).text()+"</p>");
        });
});
4

3 回答 3

1

如果我正确理解“一次打印一行”,我认为您需要在执行新调用之前清空“输出”选择器

$('#editbtn').click(function(){

    $('#out').empty();

    $('#estTable tr').filter(':has(:checkbox:checked)').find('td').each(function() {
        $('#out').append("<p>"+$(this).text()+"</p>");
    });
});
于 2013-01-12T15:16:05.553 回答
1

jsBin 演示

CSS:

.highlight{
    background:gold;
}

jQuery:

$('#estTable tr:gt(0)').click(function( e ){ 
  var isChecked = $(this).find(':checkbox').is(':checked');
  if(e.target.tagName !== 'INPUT'){
      $(this).find(':checkbox').prop('checked', !isChecked);
  }
  $(this).toggleClass('highlight');
});
于 2013-01-12T15:17:09.467 回答
1

当您使用类向源代码添加更多上下文时,这会变得容易一些:

<tr>
    <td class="select hidden">
        <input type="checkbox">
    </td>
    <td class="name">Chris</td>
    <td class="age">10</td>
</tr>

然后你可以做这样的事情:

$(document).ready(function () {
    'use strict';
    $('#estTable tbody tr').click(function (e) {
        //when the row is clicked...
        var self = $(this), //cache this
            checkbox = self.find('.select > input[type=checkbox]'), //get the checkbox
            isChecked = checkbox.prop('checked'); //and the current state
        if (!isChecked) {
            //about to be checked so clear all other selections
            $('#estTable .select > input[type=checkbox]').prop('checked', false).parents('tr').removeClass('selected');
        }
        checkbox.prop('checked', !isChecked).parents('tr').addClass('selected'); //toggle current state
    });
    $('#editbtn').click(function (e) {
        var selectedRow = $('#estTable .select :checked'),
            tr = selectedRow.parents('tr'), //get the parent row
            name = tr.find('.name').text(), //get the name
            age = parseInt(tr.find('.age').text(), 10), //get the age and convert to int
            p = $('<p />'); //create a p element
        $('#out').append(p.clone().text(name + ': ' + age));
    });
});

现场演示:http: //jsfiddle.net/Lf9rf/

于 2013-01-12T15:34:40.367 回答