Javascript 使用$(';#foo';).val()=$(';#foo';)(';:checked';)是否永远不会以true结尾?

Javascript 使用$(';#foo';).val()=$(';#foo';)(';:checked';)是否永远不会以true结尾?,javascript,jquery,Javascript,Jquery,我该如何比较这两个变量呢 这是我的密码: if ($('#<%= CheckBox1.ClientID %>').val() != $('#<%= CheckBox1.ClientID %>').is(':checked')) { /* ... */ } if($('#').val()!=$('#').is(':checked')){ /* ... */ } 它总是返回真的 如何比较这两个值?我试图捕获最后一个状态的复选框,看看它是否与当前状态相同。谢谢 您在

我该如何比较这两个变量呢

这是我的密码:

if ($('#<%= CheckBox1.ClientID %>').val() != $('#<%= CheckBox1.ClientID %>').is(':checked')) {
    /* ... */
}
if($('#').val()!=$('#').is(':checked')){
/* ... */
}
它总是返回真的


如何比较这两个值?我试图捕获最后一个状态的复选框,看看它是否与当前状态相同。谢谢

您在理解复选框和.val()函数时有一个基本错误

<input id="test" type="checkbox" value="ValueToReturnIfChecked" name="WhateverToUseInYourPost" />

$("#test").val() //will return "ValueToReturnIfChecked.

$("#test").is(":checked") //will return true or false.

$("#test").prop("checked") //will return true or false.

$("#test").attr("checked") //will return checked or empty string

.is(“:checked”)将始终返回布尔值,.val()将始终返回字符串值。在什么情况下,你期望两者相等?你想比较什么?这些返回不同的内容。@KevinB谢谢,在.is(“:checked”)上使用了String(),它允许我比较这两个。
$("#test").on("click", function(){
     $this = $(this);
     if($this.data("priorState") == $this.is(":checked")){
          //Do something
     }else{
          //The following will inject the state into the checkbox so you can track it.
          $this.data("priorState", $this.is(":checked"))
     }

});