Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将函数附加到表单元素_Javascript_Html_Css - Fatal编程技术网

Javascript 如何将函数附加到表单元素

Javascript 如何将函数附加到表单元素,javascript,html,css,Javascript,Html,Css,我想在javascript文件中的输入元素上附加一个函数,但它不能正常工作。请建议正确的语法或任何其他解决方案。我也不想使用像这样的内联html方法。这里是 document.getElementById(“name”).onfocus=hello(); 函数hello(){ 警惕(“你好”); } 改为附加事件侦听器 document.getElementById(“名称”).addEventListener(“焦点”,函数(){ 警报(“你好”) }); 好的,首先需要定义函数hello

我想在javascript文件中的输入元素上附加一个函数,但它不能正常工作。请建议正确的语法或任何其他解决方案。我也不想使用像
这样的内联html方法。这里是

document.getElementById(“name”).onfocus=hello();
函数hello(){
警惕(“你好”);
}

改为附加事件侦听器

document.getElementById(“名称”).addEventListener(“焦点”,函数(){
警报(“你好”)
});

好的,首先需要定义函数hello,然后才能将其定义为用于事件的函数

第二,当您将函数名设置为onfocus函数时,您需要删除函数名中的括号。您提供了对函数的引用,供以后使用,而不是在那里执行它

因此,这应该是可行的:

函数hello(){
警惕(“你好”);
}

document.getElementById(“name”).onfocus=hello

答案正确谢谢。当我必须传递任何参数时,如.onfocus=hello(“name”);然后您需要:
.onfocus=function(){hello(“name”)}那么我如何传递参数,比如.onfocus=hello(“name”);你为什么要这么做?你想(在现实中)实现什么。我假设你不想在获得焦点时弹出一个警告框?事实上我已经编写了一个脚本来验证表单,其中我使用内联html方法来附加函数,比如onsubmit=“CheckForm”(“form”),它工作得非常好,但是我想删除这个内联html方法,我想在外部javascript文件中附加函数以形成html文件中没有的元素。好的,假设您将CheckForm函数(不带参数)分配给
元素的onsubmit事件。运行函数后,内置javascript
this
关键字将表示触发事件的表单元素。所以你不需要传递它,它已经存在了。处理JS事件时,你唯一能传递的就是事件本身。请看这里:
function hello () {
    alert("hello");
}
document.getElementById("name").onfocus = hello;
document.getElementById("name").addEventListener("focus", function(){alert('test')}, false);