【发布时间】: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 存在多次,应该是唯一的。