2013-05-26 102 views
0
$("input[type=checkbox]").click(function(){ 
    alert("clicked"); 
    if($('#result').html().length) { 
      $('button[type="submit"]').attr('disabled','disabled'); 
     } else { $('button[type="submit"]').removeAttr('disabled'); } 
    }); 

上述代码my if语句未运行。 如果我在控制台中运行if语句,它运行良好,但只要将它嵌入到click函数中即可。该警报显示,但我的提交框不灰色。JQuery if语句未运行

任何人都知道我的代码有什么问题。

+2

是它包裹着'$(文件)。就绪()',哪些因素是'#result'? alert()是否被执行? –

+0

尝试使用'prop'方法: '$('button [type =“submit”]')。prop('disabled',true);' – undefined

+0

如果我在控制台中单独运行代码,但是,只要我嵌入代码,这部分不会运行$('button [type =“submit”]')。attr('disabled','disabled'); –

回答

0

使用本

if($('#result').text()=='') $('button').prop('disable',true); 
else $('button').prop('disable',false); 
1
  1. 确保在jQuery ready
  2. 包裹你的代码如果$(selector)不匹配任何DOM节点调用.html时,它会返回undefined。因此请删除.length。 (undefined.length - >抛出错误)
  3. 也将.html更改为.text。如果您将删除空格,则可以添加$.trim()
  4. 如果您使用的是jQuery 1.6或更高版本,请使用prop而不是attr

jQuery(function($) { 
    $("input[type=checkbox]").click(function(){ 
     alert("clicked"); 
     if($.trim($('#result').text())) { 
      $('button[type="submit"]').prop('disabled', true); 
     } 
     else { 
      $('button[type="submit"]').prop('disabled', false); 
     } 
    }); 
}); 

您可以将代码尽量减少这样的:

jQuery(function($) { 
    $("input[type=checkbox]").click(function() { 
     // Make sure myTest is an boolean: 
     var myTest = Boolean($.trim($('#result').text())); 
     // Send myTest as 2th argument: 
     $('button[type="submit"]').prop('disabled', myTest); 
    }); 
}); 
+0

可以进一步:$('button [type =“submit”]')。prop('disabled',function(){return Boolean($。trim($('#result')。text( )))?true:false;});'(但我认为'!! $。trim(/*...*/)'就像是可靠/容易) –

+0

@DavidThomas我用'布尔()'不使焦点离开脚本的主要部分。我认为'!!'不会那么清楚。 – andlrc