AddEventListener to not exists object with only Javascript

后端 未结 2 1245
鱼传尺愫
鱼传尺愫 2021-01-07 04:57

I search for the whole stackoverflow but I didn\'t get any good result against this issues.Correct me if i\'m wrong.

I want to addEventListener to object that exists

2条回答
  •  余生分开走
    2021-01-07 05:45

    jQuery does not add the event listener to each div, it attaches it to the parent.

    What you can do is attach the event to the parent, and in the event handler, see it the target is one of the buttons, then run your function

    HTML

    one
    two
    three

    JS

    document.getElementById("parent").addEventListener("click", function(event) {
         if ( event.target.className === 'my-button') {
              //Do your magic
         }
    });
    

    This way, every button you add will run your function. I don't know if the event target has the className attribute, but I suppose is rather simple to get the element based on the event.target object. Remember that older IE won't have the addEventListener function. Check here EventTarget.addEventListener - Web API Interfaces | MDN

提交回复
热议问题