首页 > 解决方案 > 如何验证复选框是否被选中?

问题描述

我目前正在尝试让我的复选框在选中时显示浏览器通知的弹出窗口。如果用户取消选中它,浏览器通知将弹出拒绝,反之亦然。

这是我现在正在尝试的一个片段,但它不起作用。

if(checkbox_id == (queue_notification)) {
        if(checkbox_state) {
          $('input#user_hop_queue_notification').is(':checked') == '1'
             if(Notification.requestPermissionre !== "granted"){
              Notification.requestPermission(function(status) {
                console.log('Notification permission status:', status);
              });
            }
          }
        else {
          $('input#user_hop_queue_notification').is(':checked')== ('0');
          if(Notification.requestPermission !== "denied"){
              Notification.requestPermission(function(status) {
                console.log('Notification permission status:', status);
              });
            }
          }
      }

标签: javascriptjqueryruby-on-railsruby

解决方案


您的代码看起来很奇怪,您似乎测试了 的值is(':checked'),但实际上没有(没有if- 语句??)。有一个checkbox_state已测试但未设置的变量?而且,您似乎在测试 的值是否is(':checked')返回字符串01. 虽然这可行,但如果您在控制台中手动测试,或查看文档,您会看到它返回trueor false,这样您的代码也可以更简单。

所以我会写你的代码如下:

  if(checkbox_id == (queue_notification)) {
    checkbox_state = $('input#user_hop_queue_notification').is(':checked'); 
    if(checkbox_state) {
      if(Notification.requestPermissionre !== "granted"){
          Notification.requestPermission(function(status) {
            console.log('Notification permission status:', status);
          });
      } 
    } else {
      if(Notification.requestPermission !== "denied"){
          Notification.requestPermission(function(status) {
            console.log('Notification permission status:', status);
          });
      }
    }
  }

如果我正确理解了您的意图,这应该会按预期工作。我们可以将变量重构掉,因为我们没有进一步使用它(但现在我想更接近您的原始代码)(它可能仍会提高可读性,所以这将是check_state保留它的一个很好的理由,但是is(:checked)本身就很不言自明)。

如果您尝试设置选中状态,则应使用以下代码:

 $('input#user_hop_queue_notification').prop('checked', true);

(如果不明显,true 将“选中”复选框,false 将取消选中)。


推荐阅读