[英]How to attach a function to a form element
我想将函数附加到javascript文件中的input元素上,但由于我想使用,请提出正确的语法或任何其他解决方案,我也不想使用像<input type="text" id="name" onfocus="hello()">
这样的内联html方法<input type="text" id="name" onfocus="hello()">
。 这是小提琴 ,
document.getElementById("name").onfocus = hello(); function hello () { alert("hello"); }
<input type="text" id="name">
我希望在输入元素获得焦点时执行该函数,但是此处该函数将立即执行,页面加载完成。 请我要纯JavaScript没有jquery。
附加事件监听器
document.getElementById("name").addEventListener("focus", function(){ alert('Hello') });
<input type="text" id="name">
document.getElementById("name").addEventListener("focus", function(){alert('test')}, false);
好的,首先,您需要先定义函数hello, 然后再将其定义为用于事件的函数。
其次,将其设置为onfocus函数时,需要从函数名称中删除括号。 您正在提供对该函数的引用,以供以后使用,而不是在那里不执行它。
因此,这应该工作:
function hello () { alert("hello"); } document.getElementById("name").onfocus = hello;
function hello () {
alert("hello");
}
document.getElementById("name").onfocus = hello;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.