[英]How do I make Javascript inside Django code listen & respond to on click events on the front end?
I have a page which has a list of products.我有一个包含产品列表的页面。 For each product, I have a button (Add to Cart).
对于每个产品,我都有一个按钮(添加到购物车)。
Once a user clicks on this button the product gets added on a side panel (aka cart).一旦用户单击此按钮,产品就会添加到侧面板(又名购物车)上。 This side panel has:
该侧面板具有:
Now, I have an event listener in my JS which would listen to click on the delete icon and then remove the product.现在,我的 JS 中有一个事件侦听器,它会侦听单击删除图标然后删除产品。 But, any clicks on the delete icons are not getting responded.
但是,对删除图标的任何点击都没有得到响应。
Funny thing is if I take the same JS code and use it in Chrome console it works.有趣的是,如果我采用相同的 JS 代码并在 Chrome 控制台中使用它,它就可以工作。 Any idea why this is not working ?
知道为什么这不起作用吗?
From what I understand you have to make a folder called static at the root directory of your app this is where you keep your JavaScript/CSS files.据我了解,您必须在应用程序的根目录下创建一个名为 static 的文件夹,这是您保存 JavaScript/CSS 文件的地方。 Then you have to let Django know where your static files are in your settings.py file.
然后你必须让 Django 知道你的静态文件在你的 settings.py 文件中的位置。 By adding the code showed below.
通过添加如下所示的代码。 I have also included how to render in the static files in your HTML file hope this helps.
我还包括如何在 HTML 文件中的静态文件中呈现希望这会有所帮助。
settings.py:设置.py:
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
STATIC_URL = '/static/'
HTML file: HTML文件:
<!DOCTYPE html>
<head>
{% load static %}
<script src="{% static 'app.js' %}"></script>
<title>Site</title>
</head>
<body>
<img src="{% static 'img.png' %}" alt="Mon image" />
{% block content %}{% endblock %}
</body>
</html>
You could change app.js and img.png depending on how you want to name your files.您可以根据您希望如何命名文件来更改 app.js 和 img.png。
There is a similar thread here: django how to include javascript in template这里有一个类似的线程: django how to include javascript in template
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.