“IF ELSE”Javascript 不工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14799607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"IF ELSE" Javascript not working
提问by user1708580
A) I have a first function which works very well :
A)我有第一个功能很好用:
if(onlyUs == '1' && idUser == '0'){
obj.after(jQuery('<div />').css({'clear':'both'}).addClass('kklike-msg').text('Only registered users can vote.'));
setTimeout(function(){
jQuery('.kklike-msg').fadeOut('normal');
},3000);
return false;
}
B) So I thought I could do the following thing :
B)所以我想我可以做以下事情:
if(idUser == '0'){
if(action == 'like'){
var ajaxAction = 'add_like';
}else{
var ajaxAction = 'remove_like';
}
}else{
if(action == 'like'){
var ajaxAction = 'add_like';
window.open('http://mywebsite.com/like')
}else{
var ajaxAction = 'remove_like';
window.open('http://mywebsite.com/remove')
}
}
C) Knowing that the original function is simply (works well):
C) 知道原始函数很简单(运行良好):
if(action == 'like'){
var ajaxAction = 'add_like';
}else{
var ajaxAction = 'remove_like';
}
But B) is not working.In both condition (Login or not), the new window is going to open. Do you have a solution ?
但是 B) 不起作用。在两种情况下(登录与否),新窗口都会打开。你有解决方案吗 ?
回答by Dan Herbert
Without knowing the typeof idUser
, it is difficult to tell what the problem is, but the most likely culprit is the use of ==
for comparison instead of ===
. JavaScript will convert the variables being compared into similar types when using ==
, which can cause some very unpredictable results in your case.
如果不知道类型的idUser
,它是很难说是什么问题,但最有可能的罪魁祸首是利用==
比较替代===
。使用 时,JavaScript 会将要比较的变量转换为类似的类型==
,这可能会在您的情况下导致一些非常不可预测的结果。
I recommend writing your code like the following. If this still does not work as you expected, you should investigate what the value of idUser
actually is. It may not be a string
which would be the cause of your problem.
我建议您编写如下代码。如果这仍然不能按您的预期工作,您应该调查实际的值idUser
是什么。它可能不是string
导致您问题的原因。
if (idUser === '0') {
if(action === 'like') {
var ajaxAction = 'add_like';
} else {
var ajaxAction = 'remove_like';
}
} else {
if (action === 'like') {
var ajaxAction = 'add_like';
window.open('http://mywebsite.com/like');
} else {
var ajaxAction = 'remove_like';
window.open('http://mywebsite.com/remove');
}
}
For a very simple example of why you should use ===
, see this blog post:
有关为什么应该使用 的一个非常简单的示例===
,请参阅此博客文章:
http://longgoldenears.blogspot.com/2007/09/triple-equals-in-javascript.html
http://longgoldenears.blogspot.com/2007/09/triple-equals-in-javascript.html