使用$('#foo').val()==$('!#foo'!).is(':checke

Using $('#foo').val() == $('#foo').is(':checked') never ends in true?

本文关键字:#foo checke is val 使用      更新时间:2024-02-12

如何比较这两个变量?

这是我的代码:

if ($('#<%= CheckBox1.ClientID %>').val() != $('#<%= CheckBox1.ClientID %>').is(':checked')) {
    /* ... */
}

这总是正确的。

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

您对checkbox和.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

编辑:附加澄清

我想我应该回答你的实际问题。答案是你不能将*.val()和*.is(":checked")进行比较,它们根本不同。如果你想跟踪过去的状态,你可以随时做:

$("#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"))
     }
});