如何将事件侦听器附加到已使用Javascript插入的元素? (没有jQuery)

时间:2017-03-17 12:30:10

标签: javascript dom

我插入一些新内容(除其他外):

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';
});

我想添加我的事件监听器。我需要能够从输入中获取价值。

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

1 个答案:

答案 0 :(得分:2)

之后,您已将内容注入DOM,您可以查询它,附加事件,获取值等,就像您使用任何其他DOM元素一样。

请考虑以下代码:

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);
    });
  }
});

其中有以下输出到控制台:

0.27
0.28

你可以找到一个JSFiddle demo here