2014-05-20 14 views
1

我正在瀏覽一本關於jquery的書,遇到了一個練習,但它不工作,在stackoverflow上檢查了一些相關的問題,並與我迄今爲止所做的檢查進行了交叉檢查,結果幾乎相同但我的工作不正常,有人可以請一個解決方案嗎?下面是代碼:禁用複選框使用jquery不工作

<form action="#"> 
Billing Address same as Shipping Address: 
<input type="checkbox" name="billingAddress" id="billingAddress" /> 
<br /> 
<br /> 
Street Address: 
<input class="baddr" type="text" name="street" id="street" /> 
<br /> 
<br /> 
City: 
<input class="baddr" type="text" name="city" id="city" /> 
</form> 

<script type="text/jscript"> 
$(document).ready(function() { 
    $("#billingAddress").click(function() { 
     if ($("#billingAddress").attr("checked") == true) { 
      alert("Id billingAddress is checked!"); 
      $(".baddr").val(""); 
      $(".baddr").attr('disabled', 'disabled'); 
     } else if ($("#billingAddress").attr("checked") == undefined) { 
      $(".baddr").removeAttr("disabled"); 
     } 
    }); 
}); 
</script> 
+0

別人給了一個答案,但作爲一個風格問題,如果你有像'如果(二==真)'其中'b'是一個布爾值,請減少到'if(b)'。 – rafalio

+1

這似乎是瞭解HTML屬性和DOM屬性之間差異的好機會:http://stackoverflow.com/q/6003819/218196, http://stackoverflow.com/q/7588846/218196,http: //stackoverflow.com/q/5874652/218196,http://stackoverflow.com/q/10280250/218196 –

回答

0

工作演示:有很多種方法,其中一個是:http://jsfiddle.net/J9vWu/

使用this並鏈接幾行的另一個版本:http://jsfiddle.net/z9xjB/http://jsfiddle.net/NzEjK/

代碼

$(document).ready(function() { 
    $("#billingAddress").click(function() { 
     if ($("#billingAddress").prop("checked")) { 
      alert("Id billingAddress is checked!"); 
      $(".baddr").val(""); 
      $(".baddr").prop('disabled', 'disabled'); 
     } else if ($("#billingAddress").prop("checked") == undefined) { 
      $(".baddr").removeAttr("disabled"); 
     } 
    }); 
}); 

或者

$(document).ready(function() { 
    $("#billingAddress").click(function() { 
     if ($(this).prop("checked")) { 
      alert("Id billingAddress is checked!"); 
      $(".baddr").val("").prop('disabled', 'disabled');; 
     } else if ($(this).prop("checked") == undefined) { 
      $(".baddr").removeAttr("disabled"); 
     } 
    }); 
}); 
+1

甚至更​​好:'this.checked'。 –

+0

@FelixKling +1對那個不滿!是的,一個即將推出的演示支持演示:http://jsfiddle.net/NzEjK/ –