我想区分提交时按下了哪个按钮/链接。我正在生产一个如此购买的产品:
var product = JSON.parse(data);
var html = '';
html += '<div>'
html += '<form class="buy-product" >';
html += '<div class="product_title">Price</div>'
html += '<div class= "product_info_2" >' + product['product_price'] + '</div>'
html += '<div class= "product_info_2" >' + product['product_description'] + '</div>'
html += '<div class="product_title">Image</div>'
html += '<div class= "product_info_2" >Coming Soon</div>'
html += '<input type="hidden" name="product_id" value="' + product['product_id'] + '" id="product_id" >'
html += '<a href="#" class="button rightButton submit" id="add-to-cart-button" style="margin-right:100px;" >Add To Cart!</a>'
html += '<a href="#" class="button rightButton submit" id="view-product-button" >Buy It Now!</a>'
html += '</form>'
html += '</div>'
$('#product .toolbar h1').html(product['product_name']);
$('#view-product').html(html);
我得知产品是这样提交的:
$('#product').on('submit', '.buy-product', function() {
var product_id = $(this).children('input[name=product_id]').val();
createPurchaseView(product_id);
jQT.goTo('#purchase');
});
但是,如何区分“添加到购物车”与“正在购买”被按下?
答案 0 :(得分:5)
将事件参数添加到回调并检查其目标属性。
$('#product').on('click', '.buy-product', function(event) {
var $target = $(event.target);
if($target.is("#add-to-cart-button") {
//Add to cart
} else if($target.is("#view-product-button") {
//Buy it now
}
});
答案 1 :(得分:0)
将单击处理程序添加到按钮中,在该按钮中向已单击的元素添加一些数据,例如:
$('.button').click(function(){
$(this).data("clicked", true);
});
然后在提交事件中检查此数据:
$('.button').each(function(){
if ($(this).data("clicked")) alert("it was me");
});