简体   繁体   English

jQuery单击td切换复选框

[英]jQuery click on td to toggle checkbox

As the title suggests, I want to be able to click on a table td OR the checkbox itself to toggle a checkbox on or off. 如标题所示,我希望能够单击表td 复选框本身来切换复选框的打开或关闭。 The solution below works when clicking on the td, but for some reason when you click on the checkbox nothing happens. 单击td时,以下解决方案有效,但是由于某些原因,当您单击复选框时,没有任何反应。 Any ideas as to what is going on here? 关于这里发生的事情有什么想法吗?

$('td').click(function (e) {
    // Toggle checkbox
    $('input:checkbox', this).prop('checked', function (i, value) {
        return !value;
    });
});

Thanks! 谢谢!

http://jsfiddle.net/Littlebob/56CnR/ http://jsfiddle.net/Littlebob/56CnR/

It's because the <input> checkbox is inside the <td> and you have attached click event to the <td> 这是因为<input>复选框位于<td>内部,并且您已将click事件附加到<td>

to overcome this, Check for the target type and if it's not input checkbox, you need to process it. 为了克服这个问题,请检查目标类型,如果未输入复选框,则需要对其进行处理。

DEMO 演示

$('td').click(function (event) {
    if (!$(event.target).is('input')) {
       $('input:checkbox', this).prop('checked', function (i, value) {
        return !value;
       });
    }
});

refer 参考

event.target 事件目标

jQuery.is() jQuery.is()

I don't know the context of your code, but you really shouldn't need any jQuery/JavaScript here. 我不知道您的代码的上下文,但是您实际上不需要在这里使用任何jQuery / JavaScript。 This can be done simply with the addition of the label element : 这可以简单地通过添加label元素来完成:

HTML 的HTML

<table>
    <tr>
        <td>
            <label><input type="checkbox" name="something" value="0"/></label>
        </td>
    </tr>
</table>

CSS 的CSS

td {
    background-color: #eee;
}

label {
    padding: 20px;
    cursor: pointer;
    display: block;
}

See the demo 观看演示

$(document).ready(function () {
$(document).on('click', 'tbody td', function (e) {
    e.stopPropagation();
    var checked= $(this).find('input[type="checkbox"]');
    checked.prop('checked', !checked.is(':checked'));
    $(this).toggleClass('selected'); // or anything else for highlighting purpose
});
$(document).on('click', 'input[type="checkbox"]', function (e) {
    e.stopPropagation();
    $(this).parent().toggleClass('selected'); // or anything else for highlighting purpose
});
});

check this JSFiddle 检查这个JSFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM