我想知道在以下结构上为动态创建的HTML元素添加事件侦听器的最短和最快方法是什么,只允许使用纯JS。 这是HTML结构:
const transmission = 'Manual'
const car_color = 'Yellow'
const model_year = 2013
const min_price = 3500000
const max_price = 4000000
const query = {
'cars.transmission_type': transmission,
'cars.color': car_color,
'cars.year': model_year,
'cars.PriceInINR': { '$gte': min_price, '$lte': max_price }
}
db.companies.aggregate([
{ '$unwind': '$cars' },
{ '$match': query }
])
这是JS结构
<div class="container">
<h1> To Do List </h1>
<input type="text" id="userInput" />
<ul id="todosHolder">
<li><span class="delete">X</span> Foo </li>
<li><span class="delete">X</span> Whatever </li>
<li><span class="delete">X</span> Yeah sure </li>
<li><span class="delete">X</span> Bar </li>
</ul>
</div>
答案 0 :(得分:2)
您可以在父级上放置一个侦听器以处理子级的事件。
//put an event listener on the parent ul
document.getElementById('todosHolder').addEventListener('click', function(e){
//if the delete was clicked, remove the li
if (e.target.classList.contains('delete')) {
e.target.parentElement.remove();
} else if (e.target.tagName === 'LI') {
//if the li was clicked, toggle the class
e.target.classList.toggle('completed');
}
});
// listen for 'enter' keypress
let inputListener = document.getElementById('userInput');
inputListener.addEventListener('keypress', function(event) {
if (event.which === 13) {
var inputText = this.value;
this.value = "";
//create new li and add it to ul
var ul = document.getElementById('todosHolder');
ul.insertAdjacentHTML('beforeend', '<li><span class="delete">X</span> ' + inputText + '</li>');
}
});
.completed { color: red; }
<div class="container">
<h1> To Do List </h1>
<input type="text" id="userInput" />
<ul id="todosHolder">
<li><span class="delete">X</span> Foo </li>
<li><span class="delete">X</span> Whatever </li>
<li><span class="delete">X</span> Yeah sure </li>
<li><span class="delete">X</span> Bar </li>
</ul>
</div>