简体   繁体   English

为什么在JavaScript中未定义event.target.value?

[英]why event.target.value is undefined in javascript?

I wrote a function as follow 我写了一个函数如下

var getVal = function(event){
   var amount = event.target.value;
   console.log(amount);
 }

Dom 多姆

<input id='myInp' type='text' onclick='getVal()'/>

Sometimes I can get the value just 1 click but sometimes I have to click several times to trigger the event.... Can any one tell me why? 有时我只需单击一下即可获得该值,但有时我必须单击几次才能触发该事件。...有人可以告诉我为什么吗? This happened on my React.JS application and my ReactNative project as well. 这发生在我的React.JS应用程序和我的ReactNative项目上。 Try a lot of time but useless at all... 尝试很多时间,但根本没有用...

Many thanks 非常感谢

The short possible solution is to pass the event object: 简短的解决方案是传递event对象:

<input id='myInp' type='text' onclick='getVal(event)'/>

I would rather suggest you to go unobtrusive instead of inline event handlers: 我宁愿建议您不要显得内向,而不要使用内联事件处理程序:

var el = document.querySelector('#myInp');
el.addEventListener('click', getVal);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM