Add Event Listener to Collection of HTML Elements

前端 未结 8 2073
执念已碎
执念已碎 2020-12-03 18:40

I know that getElementsByTagName and getElementsByClassName need an index identifier in order for the objects to be bound to an event listener.

相关标签:
8条回答
  • 2020-12-03 19:32

    You can use delegates to implement this. Get hold of a parent element to these inputs and add an event listener to that parent element. This way you will be just attaching one event and make use of event bubbling to accomplish your task. In that event listener, you might have to check the target of the event and if that target equals the input element, you can run your logic inside this condition.

    You can do something like this in your event handler function.

    // ...
    // get event and source element e = e || window.event;
    src = e.target || e.srcElement;
    if (src.nodeName.toLowerCase() !== "input") {
        return; 
    }
    // ...
    
    0 讨论(0)
  • 2020-12-03 19:38

    You can use the class too as a selector.

    var elems = document.getElementsByClassName('inputs');
    

    Then loop over these to attach event handlers.

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