<Input type = "checkbox" id = "checkbox1"/>
$ ("Input # checkbox1"). Click (function (){
Console. Log ($ (this). ATTR ('checked '));
Console. Log ($ (this). Prop ("checked "));
});
Click checkbox output:
Undefined true Click again. Undefined false indicates that if no checked is set, we should not use the ATTR ("checked") attribute. Note: Do not have spaces in the middle of the input and # checkbox1. If there is space, it indicates the descendant. We often need Li or span to contain a checkbox. No matter whether you click checkbox or Li, the corresponding event is triggered, such as the background color.
<ul> <li><input type="checkbox" name="" id=""/>li1</li> <li><input type="checkbox" name="" id=""/>li2</li> <li><input type="checkbox" name="" id=""/>li3</li> <li><input type="checkbox" name="" id=""/>li4</li></ul>
JS:
$("ul li").click(function(){ var $input=$(this).find("input"); if($input.prop("checked")) { $input.prop("checked",false); $(this).css("background-color",""); } else { $input.prop("checked",true); $(this).css("background","red"); } });
Click Li. Why can't I click checkbox. The reason is that after you select this option, input. Prop ("checked") is true, and then it is canceled again. You cannot select this option.
This does not work either:
$("ul li").click(function(){ var $input=$(this).find("input"); var count=1; if(count%2==0) { $input.prop("checked",false); $(this).css("background-color",""); } else { $input.prop("checked",true); $(this).css("background","red"); } count++; });
Because every time you click count, the value is assigned again.
Here we can use each to add count before each Li Function Definition:
$("ul li").each(function(){ var count=1; $(this).click(function(){ var $input=$(this).find("input"); if(count%2==0) { $input.prop("checked",false); $(this).css("background-color",""); } else { $input.prop("checked",true); $(this).css("background","red"); } count++; }); });