1

原始问题:我一直对应该是一个非常简单的 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(); 工作得很好,但是当它试图改变全局变量 done 时,什么也没有发生。这是脚本:

<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>

两个函数都调用得很好,表单检查有效,当所有内容都“提交”时会出现通知,唯一的问题是变量done 没有改变。感谢您到目前为止的所有帮助,有人能发现我在哪里出错了吗?

4

2 回答 2

3

您的电话"chk"根本没有执行该功能。您需要通过添加来调用它()

<a href="#" onclick="chk()"
                         ^ needed to execute function

另外,chicken 没有定义,所以在修复它之后会抛出一个错误。

Uncaught ReferenceError: chicken is not defined 

(JSFiddle)


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

不是真的。该函数的范围适用于其中的所有块。JS 没有块作用域


编辑:您问题的第 2 部分

if(done="false")
       ^ should be ==
于 2012-11-16T08:44:18.863 回答
0

我认为您应该在 onclick 属性内的函数名称后加上括号:

<a href="#" onclick="chk()">Change the variable to 3</a>
于 2012-11-16T08:44:50.050 回答