使用 jQuery 设置选中复选框
在这篇文章中,我们将学习如何在 jQuery 中设置复选框。
在 jQuery 中设置复选框已选中
此 jQuery 方法接受属性的名称,其值应更新并与元素关联。jQuery 的 .attr()
方法用于为一组匹配的项目/元素设置一个或多个属性。
语法:
attr( attributeName, value )
.attr()
技术可以方便地设置属性的值——特别是在放置多个属性或使用函数返回的值时。 .attr()
方法减少了不一致。
你可以在 .attr()
的文档中找到有关 jQuery 的 .attr()
的更多信息。
让我们举个例子。
代码 - HTML:
<input type="checkbox" id="Mumbai">Mumbai
<input type="checkbox" id="Goa">Goa
代码 - JavaScript + jQuery:
$('#Goa').attr('checked','checked');
我们描述了两个复选框,每个复选框都分配了不同的 id。你可以使用 attr()
方法访问复选框的选中属性。
此方法允许你更新要设置为默认值的复选框的属性。在任何支持 jQuery 的浏览器中运行上面的示例代码以显示以下结果。
输出:
相关文章
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
用 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 事件。