【问题标题】:I'm studying Javascript and my addeventlistener is not working on onClick我正在学习 Javascript,而我的 addeventlistener 没有在 onClick 上工作
【发布时间】:2021-11-30 23:10:52
【问题描述】:

我正在编写一个简单的应用程序,以将项目添加到购物袋中以研究 Javascript。但是,单击该元素时我的 js 代码没有注册,它没有在控制台上打印。

window.onload = function() {
    //your code here
    const fruitList = [{
            'fruit': 'Banana',
            'price': 3.9
        },
        {
            'fruit': 'Orange',
            'price': 0.7
        },

    ]

    const product = document.getElementById('products')
    ListaFrutas.map((n) => {
        product.insertAdjacentHTML('afterbegin', '<li class="fruits">' + n.fruit + '</li>');
    })

    const shoppingBag = []
    const fruitproduct = document.querySelector('.fruits')
    fruitproduct.addEventListener("onClick", handlerClick)

    function handlerClick() {
        console.log('it works')
    }
}
<div id="content-produtos" class="flex" >
  <ul id="produtos" >
  </ul>
</div>

【问题讨论】:

  • 显示的代码甚至不会到达addEventListener,因为它在尝试使用未定义的ListaFrutas 时失败。
  • 您还通过 ID products 检索元素,但您的 HTML 的 ID 为 produtos

标签: javascript html


【解决方案1】:

假设LitsaFrutas 在别处定义,您应该将“onClick”替换为“click”。

addEventListener("click", handlerClick);

另请参阅:Difference between "click" and onclick

【讨论】:

    猜你喜欢
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    • 1970-01-01
    • 1970-01-01
    • 2010-12-03
    • 1970-01-01
    相关资源
    最近更新 更多