如果我发出警报,jquery IF的行为会有所不同

use*_*455 0 javascript jquery

我想禁用我的类中未选中复选框的所有元素.但即使这被检查,我的if返回false.

$('.myClass').each(function(i, obj) {
  if (!$j('input[name='+obj.id+']').is(':checked')){  
    $j('#desc_'+obj.id).attr('disabled','disabled');              
  }        
});
Run Code Online (Sandbox Code Playgroud)

但是,如果我在if内部发出警报,它的作品!

$('.myClass').each(function(i, obj) {
  if (!$j('input[name='+obj.id+']').is(':checked')){  
    alert($j('input[name='+obj.id+']').is(':checked'));
    $j('#desc_'+obj.id).attr('disabled','disabled');              
  }        
});
Run Code Online (Sandbox Code Playgroud)

谁知道为什么?

Myl*_*les 5

Developers tend to use console.log instead, alert() behaves differently because the DOM wont load in full until AFTER the "OK" button has been clicked on the alert.

Consider using:

$('.myClass').each(function(i, obj) {
      if (!$j('input[name='+obj.id+']').is(':checked')){  
        console.log($j('input[name='+obj.id+']').is(':checked'));
        $j('#desc_'+obj.id).prop('disabled','disabled');              
      }        
    });
Run Code Online (Sandbox Code Playgroud)

For more information and documentation see:

What is console.log and how do I use it?

and

https://developer.mozilla.org/en-US/docs/Web/API/console.log

EDIT:

I would also consider using .prop over .attr, the main differences and reasons for this are highlighted here:

.prop() vs .attr()

There's no point in me re-inventing the wheel!