[英]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.