Consider the following code:
HTML:
<input type='checkbox' />
<div>Click here</div>
JS:
$(function() {
$('input').click(function() {
document.write($(this).is(':checked') ? "checked" : "unckecked");
开发者_JAVA百科 });
$('div').click(function() {
$('input').click();
});
});
When the checkbox is clicked, the output is checked
, but if "Click here" is clicked the output is unckecked
. Why is that?
Because the click
event is different from the change
event, which is where the element changes. When the <div>
does a .click()
is triggers the click
event which hasn't yet changed the state of the checkbox so when it checks it, it's in the previous state.
When you click directly on the <input>
, you've already changed the state, even if the change
event fires 2nd in order, the main point is the checkboxes checked
status has changed, before the click
handler is checking for it, so the state is current.
If you want accurate state information look for and trigger the change
event instead, like this:
$(function() {
$('input').change(function() {
$("span").append("<br />" + (this.checked ? "Checked" : "Uncecked"));
});
$('div').click(function() {
$('input').click().change();
});
});
You can give it a try here, on the off-chance this isn't a behavior question and you're wanting an external clickable area, this is how I'd do it (via a <label>
wrapping the input).
精彩评论