【发布时间】:2019-05-30 01:52:57
【问题描述】:
我想构建一个提示函数,它会一直提示直到用户输入一个值,然后返回该值。
为什么当我在强制模式下进入然后输入一个值时,这段代码返回null?任何人都可以让它工作吗?
function UserInput(text, defaultText, mandantory) {
if (typeof defaultText === 'undefined')
defaultText = '';
if (typeof mandantory === 'undefined')
return prompt(text, defaultText);
else {
var a = prompt(text, defaultText);
if (a === '') {
return UserInput(text, defaultText, mandantory);
} else {
return null;
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<button onclick="alert(UserInput('prompt with input', ''))">prompt with input</button><br/>
<button onclick="alert(UserInput('prompt with mandantory input', '', 0))">prompt with mandantory input</button>
</body>
</html>
注意:必须从 onclick="..." 调用它。
谢谢, 德让
【问题讨论】:
-
Else 返回 a 而不是在 else 中返回 null。
标签: javascript variables if-statement prompt