Javascript 什么时候 event.target.value 不是字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14736026/
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
When is an event.target.value not a string?
提问by Akshat
I came accross value = String(event.target.value || "")when a textinputs keyup/keydown event is fired.
value = String(event.target.value || "")当 textinputs keyup/keydown 事件被触发时,我遇到了。
But i'm not sure when the event.target.valueis not a string? Is this possible? When is something else passed off as an event.target.value?
但我不确定什么时候event.target.value不是字符串?这可能吗?什么时候有其他东西作为event.target.value?
采纳答案by jbabey
If the event.targetelement is not an input type element, it will not have a valueproperty. For example, if I click a divthen event.targetis a div which does not have value.
如果event.target元素不是输入类型元素,它将没有value属性。例如,如果我单击 adiv然后event.target是一个没有value.
Wrapping event.target.value || ''in String()is not necessary as it will always be either value (which is always a string or undefined) or the empty string in the case that value is undefined.
不需要换行event.target.value || '',String()因为它始终是值(始终是字符串或undefined)或空字符串(如果值为 )undefined。
See this fiddlefor a demonstration.
请参阅此小提琴以进行演示。
回答by invalidsyntax
It may help to break down what's happening here in that statement.
The key part is that event.target.value || ""evaluates first, before String() does.
分解该声明中发生的事情可能会有所帮助。关键部分是event.target.value || ""在 String() 之前先求值。
Meaning, it is checking to see if event.target.valueis null or undefined. If it IS null or undefined, it will use the blank string ""as the default value. The outcome of this statement is then passed to String().
意思是,它正在检查是否event.target.value为空或未定义。如果它为空或未定义,它将使用空白字符串""作为默认值。然后将该语句的结果传递给 String()。

