[英]AddEventListener for multiple elements doesn't work with “focus” event
我猜我在思考方面有一個基本錯誤,但我無法繞過它。
我有幾個文本字段,我想添加一個EventListener。 我將它們全部放在一個類中,並將EventListener添加到此類中。 當選擇的事件是“點擊”時,Everyhing工作完美。 但當我把它變成“焦點”時,沒有任何反應。 這是為什么?
這工作:
document.getElementById('parent').addEventListener('click', emptyField, false);
這不是:
document.getElementById('parent').addEventListener('focus', emptyField, false);
文字字段:
function emptyField(e){ var clicked = e.target; if (clicked.value == clicked.name) { clicked.value=''; if (clicked.id=='password') { clicked.type='password'; } } }
<class id="parent"> <input type="text" name="USERNAME" id="username" value="USERNAME"><br> <input type="text" name="PASSWORD" id="password" value="PASSWORD" ><br> </class>
click
事件冒泡到祖先元素。
focus
事件沒有,正是focus
的<input>
,而不是外部元素。
我認為你必須使用querySelectorAll()
來返回所有input
:
var fields = document.querySelectorAll('#parent input');
並使用循環將focus
事件附加到每個字段:
for (var i = 0; i < fields.length; i++) {
fields[i].addEventListener('focus', emptyField, false);
}
希望這可以幫助。
如果要在沒有顯式循環的情況下將事件附加到多個元素,可以使用輔助函數:
function attachEvents(elementList, eventName, handlerFunction) {
if(typeof elementList == "string")
elementList = document.querySelectorAll(elementList);
for(var i = 0; i < elementList.length; i++)
elementList[i].addEventListener(eventName, handlerFunction);
}
你這樣稱呼它:
attachEvents("#area button", "click", function(event) {
this.style.backgroundColor = "red";
});
或者像這樣:
attachEvents(document.getElementById("area").getElementsByTagName("button"), "click", function(event) {
this.style.backgroundColor = "red";
});
你並不總是想要document.querySelectorAll
- 自己動手意味着你也可以做像some_element.querySelectorAll
這樣的事情,這對於處理尚未成為文檔的一部分或者沒有唯一選擇器的東西來說非常好。
但無論如何,將循環放在輔助函數中會為你提供jquery-esque單行程,而不需要龐大的庫,它只是幾行簡單的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.