2011-12-23 37 views
0

我有一個查詢插件,我正在處理和某些函數在ajax內容加載後。問題是讓我們說我重新啓動它15次,點擊事件然後將觸發15次,當它只被點擊一次。在ajax之後重新啓動jquery插件,導致事件觸發多次

有沒有辦法讓它不會堆積如山?我打電話給addToCart onload,也從itemDetail在ajax返回後返回

謝謝!

function addToCart() 
{ 
    $(options.add_to_cart).click(function() 
    { 
    event.preventDefault(); 
    var id = $(this).attr('id'); 

    store_item_id_val = id.replace('store-item-id-', ''); 
    var quantity = $('.quantity-' + store_item_id_val); 

    if (quantity.val() < 1) 
    { 
     showError('Please enter a quantity of 1 or more.'); 
     $(quantity).val(1); 
     return this; 
    } 

    $.post($(this).attr('href'), 
    { store_item_id: store_item_id_val, quantity: quantity.val() }, 
     function (data) 
     { 
     var result = jQuery.parseJSON(data); 
     renderCart(result); 
     }); 
    }); 

    return this; 
} 

function itemDetails() 
{ 
    $('.item-details').click(function() 
    { 
    event.preventDefault(); 

    var url = $(this).attr('href'); 

    $.getJSON(url, function (result) 
    { 

     $('.modal-title').empty().html(result.title); 
     $('.modal-content').empty().html(result.html); 
     $('#modal').slideDown(100); 
     $('.ui-button').button(); 
     addToCart(); 
     $('.modal-close').click(function() 
     { 
     event.preventDefault(); 
     $('#modal').hide(); 
     }); 
    }); 
    }); 
+0

一個良好的開端應該是展示你的代碼,否則我們沒有什麼可以審查提出建議了。 – 2011-12-23 21:23:01

+0

謝謝 - 補充。 – David 2011-12-23 21:24:29

回答

1

根據您所提供的代碼,我可能會說你有一些其他代碼調用itemDetails()。每次調用itemDetails()時,它都會將click的另一個事件處理程序添加到您的.item-details。您可能要改爲做:

$(document).ready(function() 
{ 
    $('.item-details').click(function() 
    { 
    event.preventDefault(); 

    var url = $(this).attr('href'); 

    $.getJSON(url, function (result) 
    { 

     $('.modal-title').empty().html(result.title); 
     $('.modal-content').empty().html(result.html); 
     $('#modal').slideDown(100); 
     $('.ui-button').button(); 
     addToCart(); 
     $('.modal-close').click(function() 
     { 
     event.preventDefault(); 
     $('#modal').hide(); 
     }); 
    }); 
    }); 
}); 

這將使你的.item-details歸類項事件處理程序,只激發的事件一次。如果您有動態.item-details添加和刪除你應該使用:

$('.item-details').live('click', function() ... 
+0

賓果!謝謝! :) – David 2011-12-23 21:40:56

+0

嗯..這似乎不工作在IE – David 2011-12-23 21:45:32

+0

哪部分不起作用?你使用過現場嗎? – 2011-12-23 21:48:15