简体   繁体   English

Javascript:比较两个值总是不相等

[英]Javascript: comparing two values always not equal

I'm trying to do something but im struggling with a stupid bug, hope you can help me. 我正在尝试做一些事情,但是我正在努力解决一个愚蠢的bug,希望您能为我提供帮助。

As you can see in my code I have on server some check box and I attached to it a JavaScript function. 如您在代码中所见,我在服务器上有一些复选框,并为其附加了JavaScript函数。 This function gets two values (current value and original value). 此函数获取两个值(当前值和原始值)。 My problem is when this function triggers on the if it always get to the first clause and never reach the else clause and it doesn't make any sense. 我的问题是,当该功能触发的if它总是得到第一款,从来没有达到else子句,并没有任何意义。

When I used few alerts in my code this is what happens: 当我在代码中使用很少的警报时,会发生以下情况:

case 1: alert #1 original: false current: true alert #2 true 情况1: 警报#1原始: false当前:是警报#2 true

case 2: alert #1 original: false current: false alert #2 true 情况2: 警报#1原始: false当前:错误警报#2 true

As you can see, no matter what I get true on the 2nd alert. 如您所见,无论我在第二次警报中得到了什么。

Hope I managed to explain my problem. 希望我能解释我的问题。

<asp:CheckBox id="chkIsCustomQuantity" originalvalue="false" runat="server" onclick="checkChange(this.checked, this.attributes['originalvalue'].value" />

<script type="text/javascript" language="javascript">
    function checkChange(value, originalValue) {

        //i added this for debugging purpose
        alert('original: ' + originalValue + ' ' + 'current: ' + value);
        alert(value != originalValue);

        if (value != originalValue) {
             // always happens
        }
        else {
              // never happens
        }
    }

</script>

originalValue is always a string. originalValue始终是一个字符串。 value is a boolean. value是布尔值。 So, they're never equal, but when you print them out they appear identical (since they're both converted to the same string value at that point). 因此,它们永远不会相等,但是当您将它们打印出来时,它们看起来是相同的(因为此时它们都被转换为相同的字符串值)。

You can fix this in a variety of ways. 您可以通过多种方式解决此问题。 One simple way is to convert both to strings first: 一种简单的方法是先将两个都转换为字符串:

if (String(value) != String(originalValue))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM