使用javascript的非常基本的程序中的错误
Error in a very basic program using javascript
如果person
不是null
,则输出第一个条件,否则显示一个警告框。但如果输入null
它不会执行第二个条件 - 它继续使用第一个条件。
<!DOCTYPE html>
<html>
<body>
<p>Click the button to demonstrate the prompt box.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var person = prompt("Please enter your name");
if (person != null) {
document.getElementById("demo").innerHTML =
"Hello " + person + "! How are you today?";
}
else if (person == null ){
alert("How dare you ?>");
}
}
</script>
</body>
</html>
问题很可能是你实际上并没有输入 null,而你认为是。
null
是特殊的:它是一个表示缺少值的特殊值。不要与"null"
混淆,包含单词"null"或"的字符串,空字符串。
prompt()
仅在取消时返回null
。当您"输入 null"时,您可能会以"null"或"结束,具体取决于您是否在框中键入任何内容。
看:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/null
所以你的固定代码将是:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to demonstrate the prompt box.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var person = prompt("Please enter your name");
if (person != "") {
document.getElementById("demo").innerHTML =
"Hello " + person + "! How are you today?";
} else {
alert("How dare you ?>");
}
}
</script>
</body>
</html>
myFunction() 没有定义按钮何时分配事件处理程序,因此将脚本放在 head 标签中。为了检查字符串值需要输入"而不是null
我修改了你的代码,试试这个它会起作用...它对我来说工作正常。
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
var person = prompt("Please enter your name");
if (person != "") {
document.getElementById("demo").innerHTML =
"Hello " + person + "! How are you today?";
}
else {
alert("How dare you ?>");
}
}
</script>
</head>
<body>
<p>Click the button to demonstrate the prompt box.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
</body>
</html>
相关文章:
- Rails第一个应用程序错误——Errno::ENOENT
- AngularJS:未知的提供程序错误
- webpack:在MacOS上很好,在linux上加载程序错误
- 获取解析值的未知提供程序错误
- React应用程序错误'未捕获的ReferenceError:React未定义'
- IE和GMap API 2包装程序错误
- 无法将节点邮件程序错误响应从节点.js发送到角度.js
- 密钥斗篷未知提供程序错误
- 谷歌浏览器扩展名$.ajax发布事件处理程序错误
- j查询动态事件处理程序错误
- 节点 JS 取消处理程序错误事件
- Chrome 扩展程序和保管箱投放保护程序错误
- 未知提供程序错误 - AngularJS 应用程序问题
- 车把自定义帮助程序错误:“options.fn 不是函数”
- 在 yeoman 中使用动画模块编译 AngularJS 应用程序会给出未知的提供程序错误
- 如何使用 JavaScript 访问 CouchDB?标准操作程序错误
- Angularjs.获取控制器的范围.未知的提供程序错误
- Kendo UI移动滚动程序错误
- Angular js:->访问解析属性时,angular引发未知提供程序错误
- 在遍历光标和更新文档时,连接因应用程序错误而关闭