我正在调用Javascript window.prompt(),并提示用户一次提交一个整数1。如果用户在hint()窗口上单击“取消”,则该函数应终止会话,但我找不到解决该问题的函数。
我的问题是,按取消时如何终止功能?
这是我的程序:
function isOdd(n)
{
return n % 2 == 1; // Checking if the number is odd or not
}
// sentinel-controlled loop here
while (true) {
var n = Number(prompt("Enter an integer (click Cancel to terminate)", "0"));
if(n === -1) {
break;
}
if(isOdd(n)) {
alert(n + " is odd.");
}
else {
alert(n + " is even.");
}
}
// trying to find a solution for cancel button
//document.getElementById("Button ID").click()
//function cancel () {
//var cancelButton = document.getElementById( "cancel");
//}
</script>
</head>
<body>
<form action = "#">
<input id = "cancel" type = "button" value = "cancel">
</form>
<h1>Odd/Even Output</h1>
</body>
Window.prompt返回null
。您需要添加一个外壳来处理该问题。
var result = prompt("Enter an integer (click Cancel to terminate)", "0");
if(result === null) {
return;
}
var n = Number(result);
“如果用户单击”取消“按钮,则此函数返回null。”
var promptResult = prompt(...)
if(!promptResult) {
break;
}
// parse and rest of the function