我在其中插入一些新内容(除其他外):
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/