问题描述
我正在尝试通过单击li
来选中一个复选框.问题是,仅当有人单击label
而不是完整的li
时才选中该复选框(这是因为li
的宽度比label
更长!
I'm trying to check a checkbox by clicking a li
. The problem is, the checkbox is only checked when someone clicks on the label
, not the full li
(this is because the width of the li
is longer than the label
!
<ul>
<li><input id="a1" type="checkbox"><label for="a1">1</label></li>
<li><input id="a2" type="checkbox"><label for="a2">2</label></li>
<li><input id="a3" type="checkbox"><label for="a3">3</label></li>
</ul>
我已经尝试使用下面的Javascript解决此问题,但是它仍然仅在单击label
时选中此复选框.
I have tried to solve this problem using the Javascript below, however it still only checks the checkbox when the label
is clicked.
$("li").click(function(e) {
var checked = !$(this).children("input").first().prop("checked");
$(this).children("input").first().prop("checked", checked);
$(this).toggleClass("selected", checked);
});
注意:如果可能的话,我想避免使用Javascript和Jquery.
推荐答案
您不需要脚本.您可以使用label
包装该复选框和所有li
内容.给标签加上display:block
,这样它将占据" li
的整个宽度,这样,li
将可单击(例如,不是真的)
You don't need a script. You can wrap the checkbox and all the li
content with the label
. Give the label display:block
so it will "take" the full width of the li
, in this way, the li
will clickable (like, not really)
label {
display:block;
}
<ul>
<li><label for="a1"><input id="a1" type="checkbox">1</label></li>
<li><label for="a2"><input id="a2" type="checkbox">2</label></li>
<li><label for="a3"><input id="a3" type="checkbox">3</label></li>
</ul>
这篇关于单击li时无法选中复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!