javascript 如何检查 document.getElementbyId 中包含空值或未定义值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17207873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:29:49 来源:igfitidea点击:
how to check document.getElementbyId contains null or undefined value in it?
提问by Matrix
if(typeof (document.getElementById("courseId").value!=="undefined") || document.getElementById("courseId").value!==null)
{
Courseid = document.getElementById("courseId").value;
}
回答by Marco Forberg
rewrite it that way:
这样重写:
if(document.getElementById("courseId") && document.getElementById("courseId").value)
{
CourseId = document.getElementById("courseId").value;
}
回答by glosrob
If you explicitly want to check for undefined and null you can do
如果你明确想要检查 undefined 和 null 你可以做
if(document.getElementById('courseId') === null ||
document.getElementById('courseId') === undefined) {
//logic
}
回答by Eric
An input's value will never be null
or undefined - it will be the empty string, ""
.
输入的值永远不会是null
或未定义的——它将是空字符串""
.