javascript - 在 dom 中创建的按钮中访问事件监听器
问题描述
用所有代码编辑,对不起我的乱码,我是初学者
希望您能对此有所帮助,我刚刚在 dom 中创建了一个带有函数的按钮,我为该按钮提供了一个类来应用事件侦听器,由于某种原因我无法激活侦听器,有人知道吗?我做错了什么?
//this is th initial array of items, after I am changing it to an arrayof objects
let shoppingList = ['banana','apples','cherries','oranges', 'peaches'];
const list = document.querySelector('.list');
//this is the last thing I need, create new items and allow the del button
const foo=()=>{
console.log('hi');
}
const adder =(item, index, price,name)=>{
list.innerHTML += `<div class='item${[index+1]}'>${name}, price ${price} </div>`;
item[index]= {name,price};
const delElm = document.createElement('button');//the element to remove items
delElm.className = 'remove';
delElm.innerHTML = 'X';
list.appendChild(delElm);
const btndel = document.querySelector('.remove')
console.log(btndel)
btndel.addEventListener('click', foo)
}
//assign a random price to the original array
for (let i = 0; i < shoppingList.length; i++) {
let prices = i+Math.round((((Math.random()*5)+10))*100)/100;
let name = shoppingList[i];
adder(shoppingList,i,prices,name);
}
const btnElm= document.querySelector('.press');
//function to add new elements
const addItm=()=>{
const nameElm = document.querySelector('#text');
const priceElm = document.querySelector('#price');
let name = nameElm.value;
let prices = Number(priceElm.value);
let i = shoppingList.length-1;
adder(shoppingList, i, prices,name)
console.log(shoppingList)
}
console.log(shoppingList)
btnElm.addEventListener('click', addItm)
使用 HTML 进行编辑,基本上,用户可以添加填写表单的新项目,每个项目都应该可以被删除,
<input type="text" id="text" placeholder="name item">
<input type="text" id="price" placeholder="price">
<button class="press">add</button> -->
提前谢谢你
解决方案
推荐阅读
- kubernetes - 如何在 Kubernetes 上摆脱此错误“network: stat /var/lib/calico/nodename: no such file or directory”
- c++ - 为什么 std::vector 不能保存常量对象?
- gold-parser - 如何匹配 ANSI 文本文件中的重音字符?
- javascript - 如何在 Enzyme 中编写测试以检查连接/智能组件是否存在?
- codeigniter-4 - Codeigniter 4 JSON 分页
- python - 如何使用 OSError:[WinError 123] 修复 pyspark NLTK 错误?
- c# - 数字时钟中的 tick() 方法 - c#
- c# - C# 字符串数组在 int 数组中
- python - Python:移动时间序列,使它们都匹配给定的 y 值
- asp.net - pattern="." 是什么意思 在 IIS Url Rewrite 的 preCondition 属性上?