[英]Reading from a html form object in javascript only if object exists
post submit I want to javascript/client side read user input 帖子提交我想在javascript /客户端读取用户输入
var h = document.getElementById("myTEXTbox").value;
but the textbox only exists depending earlier user choices. 但文本框仅存在,具体取决于较早的用户选择。 is the an if object exists in javascript? 是javascript中存在的if对象?
check the return of getEelementById
, if an element doesnt exist it will return null, and since it is a falsey value you can use it in a if statement. 检查getEelementById
的返回,如果一个元素不存在,它将返回null,因为它是一个falsey值,你可以在if语句中使用它。
var element = document.getElementById("myTEXTbox");
var h = element ? element.value : "";
So if element
is not null
, h
will be set to element.value
otherwise it will be set to an empty string 因此,如果element
不为null
,则h
将设置为element.value
否则将设置为空字符串
If the object exists then it is an object, if not, it will return undefined! 如果对象存在则它是一个对象,如果没有,它将返回undefined!
So you can test it like this: 所以你可以像这样测试它:
var element = document.getElementById("myTEXTbox"),
h = (element)? element.value : '';
Basically, you are using this logic: If the element does exist " (element)
" or alternatively (el!=undefined)
then read the value, if not set the value of 'h'
to ''
(empty). 基本上,您正在使用此逻辑:如果元素确实存在“ (element)
”或者(el!=undefined)
则读取值,如果没有将'h'
的值设置为''
(空)。 This could be null or another value. 这可以是null或其他值。
Try this: 尝试这个:
var element = document.getElementById("myTEXTbox"),
h = element ? element.value : null;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.