Javascript event.target 在事件中未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30342873/
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
event.target is undefined in events
提问by Ramesh Murugesan
How can one use eachinput values in events? Hope my below code will explain you well.
如何each在 中使用输入值events?希望我下面的代码能很好地解释你。
HTML:
HTML:
<template name="UpdateAge">
{{#each Name}}
<div data-action="showPrompt">
<div>
Some content
</div>
<div>
<div>
Some content
</div>
</div>
<div>
Name : {{name}}
Age : <input type="text" name="age" value="{{age}}"/> //I need to access age values in event
</div>
</div>
{{/each}}
<template>
JS:
JS:
Template.UpdateAge.events({
'click [data-action="showPrompt"]': function (event, template) {
console.log(event.target.age.value); // TypeError: event.target.age.value is undefined
}
});
I dont know whether my approach is good for passing parameter values to eventsso suggestions are welcome.
我不知道我的方法是否适合将参数值传递给events因此欢迎提出建议。
回答by
the notation you are using is valid only for form elements and when event.target IS a form element.
您使用的符号仅对表单元素有效,并且当 event.target 是表单元素时。
event.target.age.value
event.targetis the element where the event occurred, event.currentTargetis the element which has attached the event handler
event.target是事件发生的元素,event.currentTarget是附加了事件处理程序的元素
if you replace divwith formand replace targetwith currentTargetthen it will work
如果您替换div为form并替换为target,currentTarget那么它将起作用
event.currentTarget.age.value
here a fiddleusing your code
回答by Cyclone
If the event is bound on the container div then the input should be searched from target, because event.targetwould give you the element whom the event was attached to.
如果事件绑定在容器 div 上,则应从目标搜索输入,因为event.target会为您提供事件附加到的元素。
To access any value within the divyou must first get access to that element and then use the properties of that element to access whatever needed - .valuein this case.
要访问 中的任何值,div您必须首先访问该元素,然后使用该元素的属性访问所需的任何内容 -.value在这种情况下。

