【问题标题】:run js on html element dynamically with Django(template)使用 Django(模板)在 html 元素上动态运行 js
【发布时间】:2020-08-13 07:15:22
【问题描述】:

我想在 h6 元素上运行 price_update() 函数

{% 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 不能与 &lt;h6&gt; 一起使用。 如何为每个产品更新&lt;h6&gt;的innerText?

【问题讨论】:

    标签: javascript django django-templates


    【解决方案1】:

    创建一个custom template tag,在那里进行算术计算,得到结果:

    • 在您的一个应用程序中创建一个名为 templatetags 的新文件夹
    • __init__.py 文件粘贴到文件夹中,以确保该目录被视为Python 包。
    • 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>
    

    【讨论】:

      【解决方案2】:
      1. Amin Mir 的

        Solution https://stackoverflow.com/a/63391216/14020019

        绝对正确,但我以不同的方式实现了该解决方案。
      2. 我的解决方案: 我在模型中添加了属性

        @property
        def final_price(self):
            f_price = self.price - (self.price * self.offer // 100)
            return f_price
        

        使用这个我直接使用了 final_price 使用. 运算符,即product.final_price

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-05-11
        • 2018-07-22
        • 2018-06-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-22
        相关资源
        最近更新 更多