首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何给出对象in列表,并根据Django中的每个列表in添加单击事件

如何给出对象in列表,并根据Django中的每个列表in添加单击事件
EN

Stack Overflow用户
提问于 2022-04-02 13:32:26
回答 1查看 53关注 0票数 0

在我的Django代码中,我有一个价格清单。现在,我给出了唯一的ID,这些ID运行良好,但是当我尝试添加一个click事件时,单击事件只对一个列表项连续工作。

代码语言:javascript
复制
      {% for price in logistic_branch_pricing %}
      <h1 id="select-delivery-location-{{price.id}}" 
   onclick="calculateDeliveryPrice()">{{ price.id }}-{{price.small_kg_price}}
      </h1>
      
      {% endfor %}

   {% for price in logistic_branch_pricing %}
   <script>
    function calculateDeliveryPrice() {
      var omo = document.getElementById("select-delivery-location-{{ price.id }}")
      omo.classList.add('d-none')
      console.log(omo)
    }
  </script>
   {% endfor %}
EN

回答 1

Stack Overflow用户

发布于 2022-04-02 13:44:44

您不必在<script>标记上添加循环,只需在javascript onclick函数中传递事件关键字,如下所示

代码语言:javascript
复制
{% for price in logistic_branch_pricing %}
   <h1 id="select-delivery-location-{{price.id}}" onclick="calculateDeliveryPrice(event)">{{ price.id }}-{{price.small_kg_price}}
   </h1>
{% endfor %}

在你的javascript里面这样做

代码语言:javascript
复制
<script>
  function calculateDeliveryPrice(e) {
      var omo = e.target
      omo.classList.add('d-none')
      var small_kg_price = omo.textContent.split('-')[1] // return small_kg_price
      console.log(omo) // returns element
      console.log(omo.id) // returns id of element
  }
</script>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71717988

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档