使用html onclick属性调用jquery函数

时间:2015-11-23 10:36:39

标签: jquery html ajax django

如何使用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函数只捕获由form生成的第一个元素并成功发送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>

0 个答案:

没有答案