当值为false时,“true”评估仍在运行。

3

我有一个非常简单的jQuery代码片段,需要检查从ajax调用返回的布尔值,并在其为true时将复选框设置为选中状态。

console.log("loc: " + r.location.defaultLocation);
if( r.location.defaultLocation == true ) {
    $('#loc-default').attr('checked',true);
}

这段代码运行在一个onclick函数中,打开一个模态窗口。如果返回的位置信息表明这是默认位置,则应该选中复选框。我们在单个页面上有5个这样的位置 - 也就是说,用户可以点击5个位置。

我遇到的问题是,即使r.location.defaultLocation返回false(根据console.log行),复选框仍然被选中。我做错了什么?

对于那些坚持true/false必须是字符串而不是布尔值的人:

这是console.info(typeof(r.location.defaultLocation));的结果:

enter image description here

如果有帮助,这是console.dir(r)的结果。(由于它包含敏感信息,group已经被模糊处理。)

enter image description here

找到问题了

显然,jQuery记得第一个标记为选中后#loc-default的状态。我在函数中添加了一个else语句,现在它可以正常工作:

if( r.location.defaultLocation == true ) {
    $('#loc-default').attr('checked',true);
}
else {
    $('#loc-default').attr('checked', false);
}

7
只需使用 if( r.location.defaultLocation ) {。这与您的问题无关,但当我看到 == true 时,感到很烦 :P - tckmn
3
使用prop代替attr - ThiefMaster
1
你确定 r.location.defaultLocation 是布尔类型而不是字符串吗? - emco
@EmCo - 是的,我尝试使用字符串比较而不是布尔值,但完全不起作用。它肯定是布尔类型的。 - EmmyS
@JayBlanchard - 这是一个ajax调用的响应。我不知道我还能说得更清楚了。 - EmmyS
显示剩余14条评论
5个回答

3
我能看到唯一的可能是defaultLocation实际上不是布尔值false,而是字符串"false",这个字符串被评估为真。

2

我认为 r.location.defaultLocation 是字符串 "false"。因此,如果您在其上使用 console.log,您将看到 "false"。但是,"false" == true 为真。

您可以使用 typeof 检查变量的类型。

console.log(typeof r.location.defaultLocation); // Log the current type of r.location.defaultLocation
console.log(typeof false); // Display boolean
console.log(typeof "false"); // Display string

它不会记录“false”,没关系,她正在连接一个字符串。 - Moritz Roessler
这不是一个字符串;我已经测试过了。它肯定是一个布尔值,真或假。 - EmmyS

2

请确保r.location.defaultLocation是布尔值。

尝试使用if (!!r.location.defaultLocation) {}将该值强制转换为布尔类型。


唯一的问题是 !!"false" 变成了 true - Mottie
@Mottie 不是 !!false 变成了 false 吗:即 !(!false) -> !(true) -> false - Mike G
@mikeTheLiar 是的,但是 "false" 是一个字符串,所以 !!"anything" 总是为 true - Mottie

1

鉴于您的代码似乎是正确的,建议尝试处理else语句并强制复选框不被选中。

if( r.location.defaultLocation == true ) {
    $('#loc-default').attr('checked',true);
} else {
    $('#loc-default').attr('checked',false);
}

1
很高兴你得到了答案!您可以通过检查Kenji的解决方案为他提供信用吗? :) - Mottie

0
首先,我会检查一下r.location.defaultLocation是什么。
 console.info(typeof(r.location.defaultLocation));

然后我会使用上面的代码继续进行:

 if (!!r.location.defaultLocation && typeof(r.location.defaultLocation)==="string") {}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接