问题
Hi i want to make checkbox checked or unchecked when i click div with text. Using jquery 1.9.1 here is a link to js fiddle
<div class="tel_show">
<input type="checkbox" name="whatever" />
visible
</div>
$("div.tel_show").live("click",function(event) {
var target = $(event.target);
if (target.is('input:checkbox')) return;
var checkbox = $(this).find("input[type='checkbox']");
if( checkbox.attr("checked") == "" ){
checkbox.attr("checked","true");
} else {
checkbox.attr("checked","");
}
});
js fiddle link
回答1:
The use of .live()
is deprecated on jQuery 1.9.x , also the use of checked
html attribute to toggle checkboxes is deprecated, use .prop('checked')
instead, your updated code should be:
$("div.tel_show").on("click",function(event) {
var target = $(event.target);
if (target.is('input:checkbox')) return;
var checkbox = $(this).find("input[type='checkbox']");
if( !checkbox.prop("checked") ){
checkbox.prop("checked",true);
} else {
checkbox.prop("checked",false);
}
});
see working fiddle
回答2:
use .prop() instead of .attr() and .live() is removed in 1.9, use .on() instead
$(document).on("click", "div.tel_show", function (event) {
var target = $(event.target);
if (target.is('input:checkbox')) {
return;
}
var checkbox = $(this).find("input[type='checkbox']");
checkbox.prop("checked", !checkbox.is(':checked'));
});
Demo: Fiddle
回答3:
I've an another version of the answer that's identical to the other two, but as it's a beginner question, I'm adding some better practices for newcomers to consider.
$('.tel_show').click(function( e ) { // emulate label on checkbox container
if ( $(e.target).is('input[type="checkbox"]') ) return;
$(this).find('input').prop('checked', function( foo, oldValue ) {return !oldValue});
});
Why:
on
is not needed (and marginally slower thanclick
) when assigning to single element. It also helps when reading code to quickly determine the event is assigned to one single element (otherwise you would use$('.parent').on('click','.children',function(){/*...*/})
)- initial selector does not need - and again is faster without - the meaningless
div
prefix. - no point in having obvious intermediate single-use variables
- make use of jQuery API for prop instead of inventing own ways to do common stuff
- selectors
:checkbox
and[type="checkbox"]
are equivalent, I chose the latter as it performs better on new browsers, but that's trivial and you can use whichever
来源:https://stackoverflow.com/questions/20017802/checkbox-inside-div-on-click-checked-or-unchecked-using-jquery-1-9-1