在 jQuery 中检查和取消检查复选框
有两种方法可以选中和取消选中复选框。对于 jQuery 1.6 以上的版本,使用 prop()
函数,对于 1.6 以下的版本,使用 attr()
函数。
在 jQuery 中使用 prop()
方法来检查和取消检查复选框
prop()
方法用于访问输入并设置其属性。此方法操作选中的属性,根据我们是否要选中或取消选中复选框来修复它的 true
或 false
。
语法:
$("#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
属性更改为 true
或 false
,具体取决于我们要选中或取消选中复选框。
将属性更改为 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
按钮后的输出:
单击否
按钮后的输出:
相关文章
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 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。