我有一组checkboxes
,具有以下结构:
<div>
<div>
<label><input type="checkbox" value="a1"/>A1</label>
</div>
<div>
<label><input type="checkbox" value="a2"/>A2</label>
</div>
...
</div>
复选框仅用于UI控件(不适用于表单提交)。我有一个关联的HTML元素,该元素具有onclick
jQuery函数,可清除所有复选框。此元素目前只是div
。从语义上讲,是否有最好的做法要说是应该是button
,a
(没有href
值)还是继续是div
?
您应该在button
状态(或button
状态中的input
元素)中使用button
元素。
为什么不a
?,因为它仅用于链接到资源。
为什么不 div
?,因为默认情况下它不可集中(对于键盘用户),并且因为它不带有隐式wai-aria角色(用于可访问性),所以您会必须手动添加两个功能,本质上是重新创建已经存在的元素: button
。
语义是一种垂死的渡渡鸟。话虽如此,这是我尝试达到似乎在很大程度上被忽略的标准的尝试。我只是使用最适合该任务的任何元素,似乎是合乎逻辑的,通用的divs和跨度是最后考虑的元素。我相信将代码从演示文稿中保留和加价也是一个主要目标,因此请使用addEventListener
代替属性事件处理程序,例如onclick
摘要
var allchx = document.getElementById('allChecks');
allchx.addEventListener('change', function(e) {
this.checked ? checkUncheck(true) : checkUncheck(false);
}, false);
function checkUncheck(chxBool) {
var chxList = document.querySelectorAll('input[name^="question"]');
var qty = chxList.length;
for (let i = 0; i < qty; i++) {
chxList[i].checked = chxBool;
}
}
<form id='survey' name='survey' action='http://httpbin.org/post' method='post'>
<fieldset class='checkboxSet'>
<legend>Product Survey</legend>
<label for='allChecks'>
<input id='allChecks' type='checkbox'>Check/Uncheck All</label>
<hr/>
<ol>
<li>
<label for='question1'>
<input id='question1' name='question1' type='checkbox' value='smoker'>Do you smoke?</label>
</li>
<li>
<label for='question2'>
<input id='question2' name='question2' type='checkbox' value='lard eater'>Do you eat lard?</label>
</li>
<li>
<label for='question3'>
<input id='question3' name='question3' type='checkbox' value='potential customer'>Do you have explosive diareha?</label>
</li>
<li>
<label for='question4'>
<input id='question4' name='question4' type='checkbox' value='definite customer'>Would you be interested in having explosive diareha in the near future?</label>
</li>
</ol>
<input type='submit'>
</fieldset>
</form>