javascript - 如何验证复选框是否被选中?
问题描述
我目前正在尝试让我的复选框在选中时显示浏览器通知的弹出窗口。如果用户取消选中它,浏览器通知将弹出拒绝,反之亦然。
这是我现在正在尝试的一个片段,但它不起作用。
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);
});
}
}
}
解决方案
您的代码看起来很奇怪,您似乎测试了 的值is(':checked')
,但实际上没有(没有if
- 语句??)。有一个checkbox_state
已测试但未设置的变量?而且,您似乎在测试 的值是否is(':checked')
返回字符串0
或1
. 虽然这可行,但如果您在控制台中手动测试,或查看文档,您会看到它返回true
or 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 将取消选中)。
推荐阅读
- java - 从 java 调用 Google Cloud Run
- javascript - 使用 JSON 数据填充 jQuery 手风琴
- c# - 无法在 Chatbot V4 框架中使用来自choicePrompt 的值
- java - 在 Spring Boot/Angular 中存储/更新图像以及实体数据
- r - ggplotly() 不在 x 轴上放置日期
- android - 如何获取房间数据库的版本号?
- kubernetes - stackdriver-metadata-agent-cluster-level 很多失败与 [2a00:1450:400c:c09::5f]:443: i/o timeout
- javascript - Bootstrap-4:将面包屑与标题对齐
- c++ - 为什么在 C++ 20 中从标准库容器中删除了比较运算符?
- python - pathlib 的 `glob` 方法在运行之间的顺序是否一致?