【问题标题】:call jquery function with html onclick attribute使用 html onclick 属性调用 jquery 函数
【发布时间】:2016-02-25 10:25:00
【问题描述】:

如何使用html按钮的onclick属性调用jquery函数?
我有一个使用 for 循环生成的 html 表单。喜欢:

{% for sku, name, mrp, sp, id in product_data_list %}
    <form id="add_to_cart" action="{% url 'add_to_cart' %}" method="POST">
    {% csrf_token %}
        <li class="item col-lg-4 col-md-3 col-sm-4 col-xs-6">
            <div class="item-inner">
            ....
            ....
         <button class="button btn-cart" type="submit" id="product_id" value="{{id}}"><span>Add to Cart</span></button>
          ....

我的 jquery 函数向 django 视图发送一个 ajax 请求。问题是我的 jquery 函数只捕获表单生成的第一个元素并成功发送 ajax 请求,但它没有处理 for 循环生成的任何其他元素。
所以我想将 jquery 函数绑定到正在生成的每个表单元素通过 for 循环。

但我不知道该怎么做。

jQuery 代码:

<script>

    jQuery(document).ready(function($){$('#add_to_cart').on('submit', function(event){
        event.preventDefault();
        $.ajax({
            url : "/add_to_cart/", // the endpoint
            type : "POST",
            cache: false,
            async: "true",
            data : { product_id : $('#product_id').val()}, // data sent with the post request

        success : function(json) {
            console.log("success");
            alert("Product Added To Cart.")
        },

        error : function(xhr,errmsg,err) {
            console.log(err);
            console.log(errmsg);
        }
    });
  });});
</script>

【问题讨论】:

  • 我猜你是在循环中添加表单。所以 id 将多次出现。在这种情况下,同一个 id 存在多次,应该是唯一的。

标签: jquery html ajax django


【解决方案1】:

请尝试

<form id="add_to_cart" action="{% url 'add_to_cart' %}" method="POST">    
{% for sku, name, mrp, sp, id in product_data_list %}

    {% csrf_token %}
        <li class="item col-lg-4 col-md-3 col-sm-4 col-xs-6">
            <div class="item-inner">
            ....
            ....
         <button class="button btn-cart" type="submit" id="product_id" value="{{id}}"><span>Add to Cart</span></button>

我想这会奏效。

【讨论】:

  • 不,这不会,因为 ajax 请求会检查第一个元素,它总是会发布第一个元素的数据。我已经试过了。
  • 我认为 product_id 在循环内重复。 " "
  • 请尽量使产品 ID 独一无二。像这样的东西“
  • 好的,我做到了id="product_id_{{id}}"。现在如何访问我的 jquery 函数中的变量?
  • var button_values = $(".button_class").map(function() { return $(this).val(); }).get();这将返回一个值数组。 'button_class' 应该是按钮的唯一类
猜你喜欢
  • 1970-01-01
  • 2011-02-09
  • 2015-07-20
  • 1970-01-01
  • 2015-07-30
  • 2023-04-07
  • 1970-01-01
  • 2019-11-06
  • 1970-01-01
相关资源
最近更新 更多