首页 > 解决方案 > 在 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> -->

提前谢谢你

标签: javascript

解决方案


推荐阅读