JavaScript:函数-如何激活取消按钮



我正在调用Javascript window.prompt((,并提示用户一次提交一个整数。如果用户在prompt((窗口上单击"取消",函数应该会终止会话,但我找不到解决这个问题的函数。

我的问题是,如何在按下取消键时终止该功能?

这是我的程序:

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>

"如果用户单击"取消"按钮,此函数将返回null。">

var promptResult = prompt(...)
if(!promptResult) {
break;
}
// parse and rest of the function
如果单击取消按钮,Window.prompt将返回null。你需要添加一个案例来处理这个问题。
var result = prompt("Enter an integer (click Cancel to terminate)", "0");
if(result === null) {
return;
}
var n = Number(result);

最新更新