在我的一生中,我无法将我的复选框设置为在页面加载时选中。 我尝试在 id 之后添加
value="true"
和 Checked="checked"
但仍然没有。有什么想法吗?
<div class="onoffswitch-container">
<span class="onoffswitch-title">Open Inline</span>
<span class="onoffswitch">
<input type="checkbox" class="onoffswitch-checkbox" id="inline">
<label class="onoffswitch-label" for="inline">
<span class="onoffswitch-inner" data-swchoff-text="OFF" data-swchon-text="ON"></span>
<span class="onoffswitch-switch"></span>
</label>
</span>
</div>
只要写“checked”就可以了
<input type="checkbox" class="onoffswitch-checkbox" id="inline" checked>
在下面添加了“true”参数,之前尝试一下,它对我有用
<input type="checkbox" class="onoffswitch-checkbox" id="inline" checked="true">
属性
checked="checked"
确实有效,简写符号就是 checked
。
<div class="onoffswitch-container">
<span class="onoffswitch-title">Open Inline</span>
<span class="onoffswitch">
<input type="checkbox" class="onoffswitch-checkbox" id="inline" checked="checked"/>
<label class="onoffswitch-label" for="inline">
<span class="onoffswitch-inner" data-swchoff-text="OFF" data-swchon-text="ON"></span>
<span class="onoffswitch-switch"></span>
</label>
</span>
</div>
我尝试了以上所有解决方案,但没有任何效果。它确实给了我一些术语来继续我的研究。我最终所做的是转到代码底部并添加
$('#inline').prop('checked', true);
这解决了我的问题。
您正在寻找
checked
内容属性。以下是官方文档中的相关片段:(生活标准):
checked content 属性是一个布尔属性,它给出输入元素的默认检查状态。添加checked内容属性时,如果控件没有脏检查性,则用户代理必须将元素的checkedness设置为true;当checked内容属性被删除时,如果控件没有脏检查,用户代理必须将元素的checkedness设置为false。
请注意,文档包含相关术语定义的链接。
如果看起来技术性太强,您可以随时访问 checked
注意: 您还可以在 MDN 上找到 问题的直接答案。
<input type="checkbox" checked />
我认为值得补充的是,设置
checked
属性将选中该框,并且不允许用户取消选中它。如果所需的功能是默认选中复选框但用户仍可以取消选中,请使用 defaultChecked
属性:
<input type="checkbox" id="inline" defaultChecked />
或
document.getElementById("inline").defaultChecked = true;