[英]run js on html element dynamically with Django(template)
I want to run price_update()
function on h6 element我想在 h6 元素上运行
price_update()
function
{% for products in allProducts %}
<div class="col-6">
Final Price: <h6 id="final_price_{{product.slug}}" onload="price_update({{products.price}},{{products.offer}}, {{product.slug}})"></h6>
</div>
<script type="text/javascript">
function price_update(price, offer, slug) {
let discounted_price = price- parseInt(price * offer / 100);
let id = "final_price_" + String(slug);
let f_price = document.getElementById(id);
f_price.innerText = discounted_price;
}
</script>
{% endfor %}
I got to know that onload
cannot be used with <h6>
.我知道
onload
不能与<h6>
一起使用。 How can update innerText of <h6>
for every product?如何为每个产品更新
<h6>
的 innerText ?
Create a custom template tag , do the arithmetic calculations there and, get the result:创建一个自定义模板标签,在那里进行算术计算,得到结果:
templatetags
templatetags
的新文件夹__init__.py
file to ensure the directory is treated as a Python package.__init__.py
文件粘贴到文件夹中,以确保该目录被视为 Python package。templatetags
folder, create a new module.templatetags
文件夹中,创建一个新模块。 This module is the one that would be loaded in your template.myapp_extras.py
myapp_extras.py
(product)
and then, add register = template.Library()
to ensure the the module is a valid tag library(product)
,然后添加register = template.Library()
以确保模块是有效的标签库 register the filter注册过滤器
@register.filter(name='price_update')
def price_update(product_id):
# Get the product by id, and calculate the price
# Return updated price
Load the module {% load myapp_extras %}
in the template then, in your template use price_update
tag:在模板中加载模块
{% load myapp_extras %}
然后,在您的模板中使用price_update
标签:
<div class="col-6">
Final Price: <h6 id="final_price_{{product.slug}}" >{{product.id|price_pudate}}</h6>
</div>
Solution https://stackoverflow.com/a/63391216/14020019 by Amin Mir absolutely correct but I've implemented the solution in different way. Amin Mir的解决方案https://stackoverflow.com/a/63391216/14020019绝对正确,但我以不同的方式实施了解决方案。
My Solution : I've added property in my model我的解决方案:我在 model 中添加了属性
@property def final_price(self): f_price = self.price - (self.price * self.offer // 100) return f_price
using this I directly used the final_price using .
使用这个我直接使用final_price使用
.
operator, ie product.final_price
运算符,即
product.final_price
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.