函数中if语句中的Javascript全局变量 - 到处都是?

时间:2012-11-16 08:39:38

标签: javascript if-statement onclick global-variables scope

原始问题:我一直在解决一个非常简单的JavaScript问题,我一直在寻找一个解决方案,但每个人都在做与我相同的事情,除了他们的脚本似乎有效。我意识到函数中if语句的范围与函数的范围不同,但我似乎无法弄明白,也无法找到解决方案:/

<head>
<script type="text/javascript">
var globalch = 1;
function chk()
{
if(chicken){
globalch = 3;
}else{
globalch = 3;
}
}
</script>
</head>
<body>
<a href="#" onclick="alert(globalch)">What is the variable?</a><br />
<a href="#" onclick="chk">Change the variable to 3</a>
</body>

这意味着完全按照它说的做,但事实并非如此。对于任何一个条件,if语句都会做同样的事情,因此它没有问题。我也尝试过使用window.globalch,window ['globalch']和其他一些建议,但无济于事。我错过了什么?我确信它是显而易见的,它将成为其中之一“哦,是的!”时刻..谢谢大家!


修改

我现在编辑了这个问题,因为我意识到这不是范围问题。现在这更深了。出于某种原因,函数 checkdetails(); 完全正常,但当它尝试更改全局变量时,没有任何反应。这是脚本:

<script type="text/javascript">
var done = "false";
function checkdetails(done){
var name = document.getElementById("name").value;
var address = document.getElementById("address").value;
var postcode = document.getElementById("postcode").value;
var city = document.getElementById("city").value;
var number = document.getElementById("number").value;
var email = document.getElementById("email").value;
if(name==""){
noty({text: "You need to enter your name."});
}else if(!address){
noty({text: "You need to enter your address."});
}else if(!city){
noty({text: "You need to enter your city."});
}else if(!postcode){
noty({text: "You need to enter your postcode."});
}else if(!number){
noty({text: "You need to enter your contact number."});
}else if(!email){
noty({text: "You need to enter your email address."});
} else {
done="true";
noty({text: "Your details have been submitted!"});
}

}
function payp(done){
if(done="false"){
noty({text: 'Please submit your details before proceeding to pay.'});
} else {
document.goandpay.submit();
}
}

这是调用函数的对象:

<a href="#" id="paypalpay" onclick="payp()">
<img src="images/paypalpay.png" style="margin-bottom:5px" alt="Proceed to the paypal payment gateway" name="Image1" width="265" height="53" border="0" id="Image1" />
</a>

两个函数调用完全正常,表单检查工作,当所有内容都“提交”时通知出现,单个问题是变量完成不变。感谢您到目前为止的所有帮助,有人可以找到我在这里出错的地方吗?

2 个答案:

答案 0 :(得分:3)

您的通话"chk"根本没有执行此功能。您需要通过添加()

来调用它
<a href="#" onclick="chk()"
                         ^ needed to execute function

此外,鸡未定义,因此在修复之后会抛出错误。

Uncaught ReferenceError: chicken is not defined 

<强> (JSFiddle)


  

我意识到函数中if语句的范围不同   函数的范围

为真。该函数的范围适用于其中的所有块。 JS没有 block-scope


编辑:问题的第2部分

if(done="false")
       ^ should be ==

答案 1 :(得分:0)

我认为你应该在onclick属性中的函数名后面加上括号:

<a href="#" onclick="chk()">Change the variable to 3</a>