简体   繁体   English

JavaScript 的点击事件在 Django 中不起作用

[英]on click event with JavaScript doesn't work in Django

this is the code for (cart.js) in the static/js folder这是 static/js 文件夹中 (cart.js) 的代码

var updateBtns = document.getElementsByClassName('update-cart')

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

and in the HTML file in the bottom:并在底部的 HTML 文件中:

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

and call the js in main.html并调用 main.html 中的 js

<script type="text/javascript" src="{% static 'js/cart.js' %}"> </script>

and I add static in the setting.py, and everything correct.我在setting.py中添加了static,一切都正确。

and everything working well, when I try to (console.log) without a button click event... the problem is only with the button event because it doesn't work并且一切正常,当我尝试(console.log)没有按钮单击事件时......问题仅在于按钮事件,因为它不起作用

Your question is not related to Django.您的问题与 Django 无关。 It seems that you do not use JavaScript correctly.您似乎没有正确使用 JavaScript 。 When the browser executes code from card.js the HTML DOM tree is not yet built.当浏览器从 card.js 执行代码时,HTML DOM 树尚未构建。 To attach JS events you need to change cart.js code to:要附加 JS 事件,您需要将 cart.js 代码更改为:

 function initUpdateBtns() { var updateBtns = document.getElementsByClassName('update-cart') for (i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'Action:', action) }) } } document.addEventListener('DOMContentLoaded', initUpdateBtns)

I might be late to answer this question, but it might help someone in the future.我可能会迟到回答这个问题,但它可能会在未来帮助某人。

Solution: Make sure your script tags:解决方案:确保您的脚本标签:

<script type="text/javascript" src="{% static 'js/cart.js' %}"> </script>

is between the body tags在body标签之间

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

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