简体   繁体   English

js“点击”功能/事件监听器问题

[英]js 'click' functionality/EventListener problem

I am trying to make an interactive button(to show a message in the console) with js, which just print a message in the console when the button is pressed.我正在尝试使用 js 制作一个交互式按钮(在控制台中显示一条消息),当按下按钮时,它只是在控制台中打印一条消息。 My js file is:我的js文件是:

console.log("hello this is from cart.js")
var updateBtns = document.getElementsByClassName('update-cart')

for(var i=0; i<updateBtns.length; i++){
  updateBtns[i].addEventListener('click', function(){
    var productId = this.dataset.product
    var action = this.dataset.action
    console.log("inside loop")
    //console.log('product ID: ', productId, "Action: ", action)
  })
}

HTML: HTML:

<button data-product="{{ i.id }}" data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button>

Here inside loop message does not show anytime.... the consol just show the following message:这里内部循环消息不会随时显示......控制台只显示以下消息:

hello this is from cart.js
DevTools failed to load SourceMap: Could not load content for chrome-extension://ndjpnladcallmjemlbaebfadecfhkepb/editor/config.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME
DevTools failed to load SourceMap: Could not load content for chrome-extension://ndjpnladcallmjemlbaebfadecfhkepb/editor/content.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME

How can I solve this problem?我怎么解决这个问题?

It appears that your code works correctly when I add it to the snippet, but I think the issue might be related to how you load in your javascript code.当我将它添加到代码段时,您的代码似乎可以正常工作,但我认为问题可能与您如何加载 javascript 代码有关。 If it is a <script> tag, could you make sure that it is included after the body tag?如果它是一个<script>标签,你能确保它包含body标签之后吗?

So like this:所以像这样:

<html>
  <head>...</head>
  <body>
    ...
    <script src="your-javascript-file.js"></script>
  </body>
</html>

The issue could be that your script is being executed before the HTML elements are created . 问题可能是在创建 HTML 元素之前正在执行您的脚本

 console.log("hello this is from cart.js") const dataset = { product: [ 'product-1', 'product-2', 'product-3' ], action: (product) => { alert(product); } } const updateBtns = document.getElementsByClassName('update-cart') for (let i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function() { const productId = dataset.product[i] const action = () => { dataset.action(productId) }; action(); //console.log('product ID: ', productId, "Action: ", action) }); }
 <button class="update-cart">1</button> <button class="update-cart">2</button> <button class="update-cart">3</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM