使用jQuery检查复选框时如何执行操作?

Kei*_*gan 15 checkbox jquery

我想在用户检查复选框时执行操作,但我无法让它工作,我做错了什么?

所以基本上,用户进入我的页面,勾选框,然后弹出警报.

if($("#home").is(":checked"))
{
      alert('');
}
Run Code Online (Sandbox Code Playgroud)

Joe*_*oel 26

您正在寻找的是一个事件.JQuery提供了简单的事件绑定方法

$("#home").click(function() {
    // this function will get executed every time the #home element is clicked (or tab-spacebar changed)
    if($(this).is(":checked")) // "this" refers to the element that fired the event
    {
        alert('home is checked');
    }
});
Run Code Online (Sandbox Code Playgroud)


Zol*_*tan 18

实际上change()这个解决方案的功能要好得多,因为它适用于javascript生成的操作,例如通过脚本选择每个复选框.

$('#home').change(function() {
   if ($(this).is(':checked')) {
      ... 
   } else {
      ...
   }
});
Run Code Online (Sandbox Code Playgroud)