簡體   English   中英

使用 Django(模板)在 html 元素上動態運行 js

[英]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>
  1. Amin Mir的解決方案https://stackoverflow.com/a/63391216/14020019絕對正確,但我以不同的方式實施了解決方案。

  2. 我的解決方案:我在 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM