为什么函数中的简单提示不起作用?

时间:2019-10-25 17:38:18

标签: javascript

在此页面中,只有当在主体部分中直接调用javascript提示时,如果我们尝试调用函数show()或showIN()(头中的第一个部分,主体中的第二个部分),则var未定义。为什么呢

<!DOCTYPE html>
<html>
<head>
<script>
//called by button 2 "show" : doesn't work, u=undefined
function show(){
    var u = prompt("What 3 ?");
    alert("u = "+ u);
    alert("qu = "+ qu);
}
</script>

</head>
<body onload= "show();">
<script>
// this works:
var qu = prompt("What 1 ?");
    alert("qu = "+ qu);

// called by button two "showIN": doesn't work, w=undefined
function showIN(){
    var w = prompt("What 4 ?");
    alert("qu = "+ qu);
    alert("w = "+ w);
}
</script>

<button id = "one" onClick = "show();">show</button>
<br/>
<button id = "two" onClick = "showIN();">showIN</button>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

<!DOCTYPE html>
<html>
<head>

</head>
<body onload= "show();">
<script>
//called by button 2 "show" : doesn't work, u=undefined
function show(){
    var u = prompt("What 3 ?");
    alert("u = "+ u);
    alert("qu = "+ qu);
}
</script>
<script>
// this works:
var qu = prompt("What 1 ?");
    alert("qu = "+ qu);

// called by button two "showIN": doesn't work, w=undefined
function showIN(){
    var w = prompt("What 4 ?");
    alert("qu = "+ qu);
    alert("w = "+ w);
}
</script>

<button id = "one" onClick = "show();">show</button>
<br/>
<button id = "two" onClick = "showIN();">showIN</button>
</body>
</html>

您需要将脚本放置在“身体”而不是“头部”内。请检查代码段。