如何查找提交中使用的按钮

Dev*_*xon 2 javascript forms jquery

我试图区分提交时按下了哪个按钮/链接.我正在生成一个如此购买的产品:

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);?
Run Code Online (Sandbox Code Playgroud)

我得到的产品是这样提交的:

$('#product').on('submit', '.buy-product', function() {
    var product_id = $(this).children('input[name=product_id]').val();
    createPurchaseView(product_id);
    jQT.goTo('#purchase');
});?
Run Code Online (Sandbox Code Playgroud)

但是,如何区分"添加到购物车"和"立即购买"被按下?

Dav*_*ave 5

将event参数添加到回调并检查其target属性.

$('#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
    }
});
Run Code Online (Sandbox Code Playgroud)

jQuery event.target页面