Why does the checkbox attribute "checked" return the actual value opposite to it on a click event?

I have the following HTML

<li><input type="checkbox" /><label>This is the label!</label></li>

I linked the click event to the sheet and gave the click event to the bubbles before li before doing anything else.

$('li').each(function(i){
  var item = $(this);
  var checkbox = $("input[type='checkbox']", item);

  item.bind('click', function(e){
    var isChecked = checkbox.is(':checked');
    console.log(isChecked);
    e.stopPropagation();
  });
});

Starting from the unchecked flag when the click event occurs, isChecked returns true when I click on this flag, but returns false when I click on the label or li. Does anyone know why?

[EDIT:] To demonstrate this problem, see http://jsfiddle.net/nYbf6/2/ .

  • Check the box in the first one.
  • Click inside the second one, but not on the label or check box.

, , , 'checked' , , .

[EDIT:] : http://www.bennadel.com/blog/1525-jQuery-s-Event-Triggering-Order-Of-Default-Behavior-And-triggerHandler-.htm. , , .

+3
3

. , false, click, . , onclick , , .

+2

click, :

$('li').click(function(e) {
  var isChecked = $(':checkbox:checked', this).length > 0;
  console.log(isChecked);
  e.stopPropagation();
});

<li>, , .

, , true, li, , . , , , . , , , true , .

, , for, :

<li>
  <input id="myInput" type="checkbox" />
  <label for="myInput">This is the label!</label>
</li>

, , .

+1

:

<li>
  <input type='checkbox' value='foo' id='myFavoriteCheckbox'>
  <label for='myFavoriteCheckbox'>The Label</label>
</li>

, , . .attr('checked'), , click . , , . , click , - , "checked" , , .

+1

Source: https://habr.com/ru/post/1739546/


All Articles