【问题标题】:How to do an action when a checkbox is checked with jQuery?使用 jQuery 检查复选框时如何执行操作?
【发布时间】:2019-07-28 04:43:07
【问题描述】:

当用户选中一个复选框时,我想执行一个操作,但我无法让它工作,我做错了什么?

所以基本上,用户访问我的页面,勾选框,然后弹出警报。

if($("#home").is(":checked"))
{
      alert('');
}

【问题讨论】:

    标签: jquery checkbox


    【解决方案1】:

    您要查找的内容称为事件。 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');
        }
    });
    

    【讨论】:

    • 这么多年过去了,你的回答仍然对我有帮助!!谢谢!
    【解决方案2】:

    实际上,change() 函数更适合此解决方案,因为它适用于 javascript 生成的操作,例如通过脚本选择每个复选框。

    $('#home').change(function() {
       if ($(this).is(':checked')) {
          ... 
       } else {
          ...
       }
    });
    

    【讨论】:

      【解决方案3】:

      您需要使用此处描述的 .click 事件:http://docs.jquery.com/Events/click#fn

      所以

      $("#home").click( function () {
          if($("#home").is(":checked"))
          {
            alert('');
          }
      });
      

      【讨论】:

        【解决方案4】:
        $("#home").click(function() {
            var checked=this.checked;
            if(checked==true)
                {
                 // Stuff here
                }
            else
                {
                //stuff here
                }
        });
        

        【讨论】:

          【解决方案5】:
          $( "#home" ).change(function() {
              if(this.checked){
                  alert("The Check-box is Checked"); // Your Code...
              }else{
                  alert("The Check-box is Un-Checked"); // Your Code...
              }
          });
          

          【讨论】:

          • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
          【解决方案6】:

          在某些情况下,当您拥有动态内容时,您可以使用以下代码:

          $(function() {
            $(document).on('click','#home',function (e) {
              if($(this).is(":checked")){
                alert('Home is checked')
              }else{
                alert('Home is unchecked')
              }
            });
          });
          

          【讨论】:

            猜你喜欢
            • 2011-05-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-11-06
            • 2011-10-14
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多