以下代码无效,无法理解原因。我做错了什么?
$(function() {
var advanced = localStorage['advanced-search'];
alert(advanced);//this shows true
if((advanced == "true")|(advanced==true)){
//Code never reaches here
alert('click');
$('#advanced-search').trigger('click');
localStorage['advanced-search'] = false;
}
});
答案 0 :(得分:4)
检查OR运算符。它应该像 -
if((advanced == "true")||(advanced==true)){
答案 1 :(得分:3)
此表达式不起作用:
if((advanced == "true")|(advanced==true)){
这就足够了:
if(advanced) {
因为"true"
作为字符串也是“真实的”。
答案 2 :(得分:1)
你错过了额外的|:
$(function() {
var advanced = localStorage.getItem['advanced-search'];
alert(advanced);//this shows true
if((advanced == "true") || (advanced==true)){
//Code never reaches here
alert('click');
$('#advanced-search').trigger('click');
localStorage['advanced-search'] = false;
}
});
答案 3 :(得分:1)
OR运算符必须是两个|
..像这样:
if((advanced == "true") || (advanced==true)){
如果变量advanced
是BOOLEAN,那么您只需使用它:
if(advanced) {
// code here..
}
答案 4 :(得分:1)
我认为你的javascript代码有误。所以你不能使用“|”而不是“||” 所以尝试通过以下代码解决您的错误。
$(function() {
var advanced = localStorage.getItem['advanced-search'];
alert(advanced);//this shows true
if((advanced == "true")||(advanced==true)){
//Code never reaches here
alert('click');
$('#advanced-search').trigger('click');
localStorage['advanced-search'] = false;
}
});
答案 5 :(得分:1)
正如你所说,一个正确的OR运算符仍然无效,我怀疑它一定是问题。
检查这个小提琴: http://jsfiddle.net/VTfQU/
使用此代码简化if
条件:
var advanced = localStorage.getItem['advanced-search'];
advanced = advanced.toString().toLowerCase();
if (advanced == "true") {
$('#advanced-search').trigger('click');
localStorage['advanced-search'] = "false";
}
我们的想法是将您的数据转换为小写,然后只检查该值的条件。我添加toString()
只是为了安全,无论如何从本地存储中获取值总是一个字符串。