AddEventListener for multiple elements doesn't work with “focus” event

前端 未结 3 1914
孤城傲影
孤城傲影 2021-01-25 19:17

I\'m guessing I have a basic error in thinking but I just can\'t get around it.

I have a couple of text fields which I want to add an EventListener to. I put them all i

3条回答
  •  轮回少年
    2021-01-25 19:57

    If you want to attach an event to several elements without an explicit loop, you can use a helper function:

        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);
        }
    

    You call it like this:

        attachEvents("#area button", "click", function(event) {
                this.style.backgroundColor = "red";
        });
    

    Or like this:

        attachEvents(document.getElementById("area").getElementsByTagName("button"), "click", function(event) {
                this.style.backgroundColor = "red";
        });
    

    You don't always want document.querySelectorAll - doing it yourself means you also do things like some_element.querySelectorAll which is really nice when working with things that aren't yet part of the document, or have no unique selector.

    But regardless, putting the loop in a helper function gives you that jquery-esque one-liner without a huge library, it is just a few lines of simple code.

提交回复
热议问题