[英]run js on html element dynamically with Django(template)
我想在 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 %}
我知道onload
不能與<h6>
一起使用。 如何為每個產品更新<h6>
的 innerText ?
創建一個自定義模板標簽,在那里進行算術計算,得到結果:
templatetags
的新文件夾__init__.py
文件粘貼到文件夾中,以確保該目錄被視為 Python package。templatetags
文件夾中,創建一個新模塊。 該模塊是將加載到您的模板中的模塊。 類似於: myapp_extras.py
(product)
,然后添加register = template.Library()
以確保模塊是有效的標簽庫注冊過濾器
@register.filter(name='price_update')
def price_update(product_id):
# Get the product by id, and calculate the price
# Return updated price
在模板中加載模塊{% load myapp_extras %}
然后,在您的模板中使用price_update
標簽:
<div class="col-6">
Final Price: <h6 id="final_price_{{product.slug}}" >{{product.id|price_pudate}}</h6>
</div>
Amin Mir的解決方案https://stackoverflow.com/a/63391216/14020019絕對正確,但我以不同的方式實施了解決方案。
我的解決方案:我在 model 中添加了屬性
@property def final_price(self): f_price = self.price - (self.price * self.offer // 100) return f_price
使用這個我直接使用final_price使用.
運算符,即product.final_price
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.