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

前端 未结 3 1884
孤城傲影
孤城傲影 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:47

    The click event bubbles up to ancestor elements.

    The focus event does not, and it is the <input> that is being focussed, not the outer element.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-25 20:12

    I think you have to use querySelectorAll() that will return all the inputs :

    var fields = document.querySelectorAll('#parent input');
    

    And use loop to attach focus event to every field :

    for (var i = 0; i < fields.length; i++) {
        fields[i].addEventListener('focus', emptyField, false);
    }
    

    Hope this helps.

    0 讨论(0)
提交回复
热议问题