迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

在 jQuery 中检查和取消检查复选框

作者:迹忆客 最近更新:2024/03/24 浏览次数:

有两种方法可以选中和取消选中复选框。对于 jQuery 1.6 以上的版本,使用 prop() 函数,对于 1.6 以下的版本,使用 attr() 函数。


在 jQuery 中使用 prop() 方法来检查和取消检查复选框

prop() 方法用于访问输入并设置其属性。此方法操作选中的属性,根据我们是否要选中或取消选中复选框来修复它的 truefalse

语法:

$("#checkbox_name").prop("checked", true);

根据 W3C 表单的定义,checked 属性是一个布尔属性,这意味着如果元素存在,则关联的属性是实际的——即使质量没有值或设置为 false

例子:

$(document).ready(function () {
            $(".clickCheck").click(function () {
                $("#chechId").prop("checked", true);
            });
            $(".clickUncheck").click(function () {
                $("#chechId").prop("checked", false);
            });
        });

这里演示

clickCheck 是按钮 Yes 的类名,而 clickUncheck 是按钮 No 的类名。同样,#chechId 是这里使用的复选框的 id 名称,用于选中和取消选中一个复选框。

输出:

在这里,你可以看到两个按钮,即。当你单击按钮时,它将在触发复选框属性时检查复选框,即 true

同样,当你单击按钮时,它将取消选中复选框,因为它会触发复选框属性,即 false


在 jQuery 中使用 attr() 方法检查和取消选中复选框

它与早期的方法相同,但更适合早期的 jQuery 版本。attr() 方法用于访问输入并设置其属性。

我们必须将 checked 属性更改为 truefalse,具体取决于我们要选中或取消选中复选框。

将属性更改为 true 时,需要提供 click() 方法以确保修改选项组中的选项。

语法:

$("#checkbox_name").attr("checked", true);

例子:

$(document).ready(function() {
                $(".clickCheck").click(function() {
                    $("#chechId").attr("checked", true);
                });

                $(".clickUncheck").click(function() {
                    $("#chechId").attr("checked", false);
                });
            });

这里演示

使用 attr() 方法的输出与 prop() 方法的输出相同。

运行代码后的输出:

点击 Yes 按钮后的输出:

单击按钮后的输出:

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

jQuery 触发点击

发布时间:2024/03/24 浏览次数:186 分类:JavaScript

在今天的文章中,我们将学习 jQuery 中的触发点击事件。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便