用jquery检查所有复选框 [英] Check all checkboxes with jquery

查看:127
本文介绍了用jquery检查所有复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$(document).ready(function(){
    function set_checked {
        alert('test'); 
        $('*:checkbox').attr('checked', checked);
    }
}); 

和这个html

<input onclick="set_checked()" value="Check all" type="button" />

由于某种原因不起作用。没有警报框或没有。

Does not work for some reason. No alert box or nothing.

推荐答案

您有几个问题,


  • set_checked 中缺少括号

  • 未定义变量 / li>
  • onclick 引用了全球化的全局函数

  • missing parentheses in set_checked function definition
  • undefined variable checked
  • onclick references global function that isnt really global

使用jQuery,最好使用jQuery click 方法将click事件添加到元素。
这是如何使用jQuery正确地做到这一点。

With jQuery it is better to add the click event to an element with the jQuery click method. Here is how to correctly do this with jQuery.

$(document).ready(function(){
    // If you want to use the `set_checked` function elsewhere do this
    function set_checked() {
        $('*:checked').attr('checked', true);
    }
    $('#check_all').click(set_checked);

    // If you are only doing `set_checked` on the button press do this
    $('#check_all').click(function() {
        $('*:checked').attr('checked', true);
    });
});

<input id="check_all" value="Check all" type="button"/>

这篇关于用jquery检查所有复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆