简体   繁体   中英

How can I attach an event listener to an element that has itself been inserted with Javascript? (without jQuery)

Where I insert some new content (among other things):

var addedaccessories = false;

//open recommended accessories
selectPlan.addEventListener('change', function() {
  accessories.classList.add('accessories--open');

  instrumentformbtn.classList.add('instrument-form__btn--enabled');
  price.innerHTML = `
<div class="priceinfo__top"><span class="price__largetext">Your plan:</span> ${selectPlan.value} per month for 36 months</div>
<div class="priceinfo__btm">First installment of ${selectPlan.value} payable on checkout</div>
`;
  price.style.paddingTop = 0;
  price.style.paddingBottom = 0;

  if (addedaccessories == false) {
    accessories.innerHTML += `<div>
   <div class="checkbox_container"> <input value="0.27" id="stand" type="checkbox"><label for="stand">Opus LMS02 lightweight folding music stand supplied with carrying bag in black</label>
    <legend>£0.27p for 60 months</legend></div>
    <br>
       <input value="0.99" id="shoulderrest" type="checkbox"><label for="shoulderrest">Kun violin shoulder rest 4/4</label>
    <legend>£0.99p for 60 months</legend>
    </div>`;
    addedaccessories = true;
  }

  selectplanmessage.style.display = 'none';
});

Where I want to add my event listener. I need to be able to get the value out of the inputs.

accessories.addEventListener('click', function(e) {
  if (e.target.tagName == 'LABEL') {
    console.log('worked');
  }
});

After you have injected content into the DOM, you can query for it, attach events, grab values, etc, just like you would any other DOM element.

Consider the following code:

var accessories = document.querySelector('.accessories');
var addedaccessories = false;


if (addedaccessories === false) {
  // inject content into the DOM
  accessories.innerHTML += '<input value="0.27" id="stand" type="checkbox"><label for="stand">Stand</label><br/><input value="0.28" id="mic" type="checkbox"><label for="mic">Mic</label>';
}

accessories.addEventListener('click', function(e) {
  if (e.target.tagName === 'LABEL') {
    // now that content has been injected, you can query 
    // for it like you normally would
    var inputs = document.querySelectorAll('.accessories input[type=checkbox]');

    // now grab the value out of the injected elements
    inputs.forEach(function(input) {
      console.log(input.value);
    });
  }
});

Which has the following output to the console:

0.27
0.28

You can find a JSFiddle demo here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM