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

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

我想在其中添加事件监听器。我需要能够从输入中获取值(value)。

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

最佳答案

将内容注入(inject) 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 .

关于javascript - 如何将事件监听器附加到本身已使用 Javascript 插入的元素? (没有 jQuery),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42857618/

相关文章:

javascript - html 或 js - 在页面中创建大量类似的 html 标签

javascript - 如果其中一个 <li> 更改位置,则立即在多个 <ul> 中移动列表元素顺序

javascript - 如何自动单击带有 JavaScript 的浏览器按钮?

javascript - Bootstrap : Collapse and Tooltip together

javascript - 如何获取/设置当前页面 URL(跨时空浏览器版本)

javascript - 获取页面上的所有节点,除了那些具有特定节点作为祖先的节点

javascript - replaceWith 后的 Dom 就绪事件

javascript - 下载pdf.js中base64生成的pdf

javascript - Jquery 验证未应用于字段

php - 上传文件夹