Add Event Listener to Collection of HTML Elements

前端 未结 8 2071
执念已碎
执念已碎 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:17

    Adding eventlistener to each of them is not advisable. May be this can help:

    http://jsfiddle.net/b8gotLL6/

    document.getElementById('parent').addEventListener('click', function(e){
    alert(e.target.value);
    })
    

    And if you only want to do using getElementsByTagName or getElementsByClassName, then i guess you need to iterate for the array returned.

    0 讨论(0)
  • 2020-12-03 19:18

    It's pretty simple like @Rutwick Gangurde said. Once you get the elements you just need to loop through and attach the event.

    var inputElem = document.getElementsByTagName('input');
    
    for(var i = 0; i < inputElem.length; i++) {
    
        inputElem[i].addEventListener('click', function(){
            alert(this.value);
        }, false);
    }
    

    Here it is in a fiddle: http://jsfiddle.net/wm7p0a77/

    0 讨论(0)
  • 2020-12-03 19:25

    you can try like this:first get all the element of the particular type the loop through it.

    var elems = document.getElementsByClassName('inputs');
    for(var i = 0; i < elems.length; i++) {
    
        elems[i].addEventListener('click', function(){
            alert(this.value);
        }, false);
    }
    <input class="inputs" type="submit" value="Hello" />
    <input class="inputs" type="submit" value="World" />

    0 讨论(0)
  • 2020-12-03 19:25
    var i=0, inputElem = document.getElementsByTagName('input'), len = inputElem.length;    
    while(i < len){
      inputElem[i].addEventListener('click', function(){
          alert(this.value);
      }, false);
     i++;
    }
    
    0 讨论(0)
  • 2020-12-03 19:27

    First, use getElementsByClassName, instead of getElementsByTagName. Then Loop through them, adding the event listener like this:

    var inputElem = document.getElementsByClassName('inputs');
    var i;
    for (i = 0; i < inputElem .length; i++) {
        inputElem [i].addEventListener('click', (function(i) {
            return function() {
               alert(this.value);
            };
        })(i), false);
    }
    

    Here it is on jsfiddle

    0 讨论(0)
  • 2020-12-03 19:30

    Try querySelectorAll method.

    var inputElem = document.querySelectorAll('input');
    

    Which returns a NodeList and you can loop through the array to add the event listeners.

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