页面加载后使用 JavaScript 将复选框设置为 Checked
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38316464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set Checkbox to Checked with JavaScript after page Load
提问by dubesor
I've got a small challenge in trying to set this checkbox element on my page to checked, after the page loads:
在页面加载后,我在尝试将页面上的此复选框元素设置为选中时遇到了一个小挑战:
<input type="checkbox" id="1403317">
<input type="checkbox" id="1403317">
Challenges:
1. This <input>
can only be called by its idsince there's no nameattribute set.
2. The JS code to do this cannot be placed inside the <head></head>
tag - I don't have access to that part of the code in this use case so this must work somewhere in <body></body>
.
挑战:
1.由于没有设置name属性,<input>
因此只能通过其id调用。
2. 执行此操作的 JS 代码不能放在标签内 - 在这个用例中我无权访问那部分代码,所以这必须在.<head></head>
<body></body>
Here's how I've tried to do this so far (before the closing </body>
tag), but with no effect. Is something wrong with my syntax?
到目前为止,这是我尝试这样做的方法(在结束</body>
标记之前),但没有效果。我的语法有问题吗?
<script type="text/javascript">
window.onload = function() {
document.getElementById("1403317").checked = true;
}
</script>
回答by Will Hamic
This should do what you are looking for. It works correctly in the snippet.
这应该做你正在寻找的。它在代码段中正常工作。
window.onload = onPageLoad();
function onPageLoad() {
document.getElementById("1403317").checked = true;
}
<input type="checkbox" id="1403317">
回答by Arif
try this one maybe ?
试试这个吧?
$(document).ready(function() {
$('#1403317').attr('checked', true)
};