简体   繁体   English

使li选择复选框

[英]Make li select checkbox

I've got a script which checks a checkbox when the span of an li is clicked. 我有一个脚本,当单击lispan时会检查一个复选框。 My problem is that the width of the li is longer than the span and therefore, part of the li doesn't check the checkbox. 我的问题是li的宽度大于span ,因此, li一部分未选中该复选框。

 $('ul.myclass li span').click( function() { var $cb = $(this).parent().find(":checkbox"); if (!$cb.prop("checked")) { $cb.prop("checked", true); } else { $cb.prop("checked", false); } }); 
 .myclass li span { margin-left: 5px; } li { background: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="myclass"> <li><input type="checkbox"><span>some text</span></li> <li><input type="checkbox"><span>some text</span></li> <li><input type="checkbox"><span>some text</span></li> </ul> 

JsFiddle: http://jsfiddle.net/7w82S/89/ JsFiddle: http : //jsfiddle.net/7w82S/89/

Use the appropriate HTML <label> element to associate the text with the <input> : 使用适当的HTML <label>元素将文本与<input>关联:

<ul class="myclass">
    <li><label><input type="checkbox"><span>some text</span></label></li>
    <li><label><input type="checkbox"><span>some text</span></label></li>
    <li><label><input type="checkbox"><span>some text</span></label></li>
</ul>

With display: block; 带有display: block; (for the <label> element's style) to fill its ancestor <li> and the desired behaviour is automatic, requiring no JavaScript. (用于<label>元素的样式)以填充其祖先<li> ,并且所需的行为是自动的,不需要JavaScript。

if i got the question right you can do this 如果我的问题正确,你可以这样做

$('ul.myclass li').click( function() {
   var $cb = $(this).find(":checkbox");
    if (!$cb.prop("checked")) {
        $cb.prop("checked", true);
    } else {
        $cb.prop("checked", false);
    }
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM