【问题标题】:How to verify if a check box is checked?如何验证复选框是否被选中?
【发布时间】:2019-09-26 15:51:06
【问题描述】:

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

这是我现在正在尝试的一个 sn-p,但它不起作用。

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);
              });
            }
          }
      }

【问题讨论】:

  • 这里的问题是什么? javascript代码是否没有正确确定复选框是否被选中(也就是发布到控制器的信息是否正确?),或者您无法保存接收到的参数?
  • 我会编辑我的问题

标签: javascript jquery ruby-on-rails ruby


【解决方案1】:

NotificationApi 是用户也可以拒绝的东西,所以即使您将Notification.permission 属性设置为granted 也不起作用。因此,您最好的机会是使用Notification.requestpermission 方法并检查用户是否已授予通知访问权限,然后使用通知 api 显示通知。谢谢。

【讨论】:

    【解决方案2】:

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

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

      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 将取消选中)。

    【讨论】:

      猜你喜欢
      • 2017-06-07
      • 2019-03-05
      • 2011-04-04
      • 2019-03-16
      • 2018-09-24
      • 2018-03-23
      • 2017-06-24
      • 2013-01-25
      相关资源
      最近更新 更多