簡體   English   中英

如何將事件偵聽器附加到本身已使用Javascript插入的元素上? (沒有jQuery)

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

我在其中插入一些新內容的地方(以及其他內容):

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

你已經注入到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 演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM