簡體   English   中英

Ajax請求后的jQuery

[英]Jquery after Ajax request

我提出了一個ajax請求,該請求替換了我網頁中的html。 現在,我必須“聽”到用ajax(“ .button2”)替換的按鈕。 我知道ajax可用於異步調用,因此ajax調用后我的源頁面不會更改。 這是我的代碼。

  $(document).ready(function(){

  $(".button").on("click", function(){
    var product = $(this).parent().parent();
    var product_id = product.children(":first").text();
    var quantity = product.find(".selectBoxCat :selected").text();
    Cookies.set(product_id, quantity, {expires: 1});

    $.ajax({
     url: "/prog/php/updateCart.php",
     dataType: "html",
     cache: false,
     success: function(data) {
       $(".shopping-cart").replaceWith(data);
       //update the cart
       $(".badge").text(Object.keys(Cookies.get()).length);
     }
   });
  });



 $(".button2").on("click", function(){
    alert("success"); //just a test
 });  
});

此代碼對我不起作用。 Button2是ajax調用后添加到網頁中的按鈕。 我怎么聽這個按鈕?

您聲明

$(".button2").on("click", function(){
 alert("success"); //just a test
}); 

如果此按鈕不存在,則事件不是盲目的。 嘗試這個:

$(document).ready(function(){

$(".button").on("click", function(){
 var product = $(this).parent().parent();
 var product_id = product.children(":first").text();
 var quantity = product.find(".selectBoxCat :selected").text();
 Cookies.set(product_id, quantity, {expires: 1});

 $.ajax({
  url: "/prog/php/updateCart.php",
  dataType: "html",
  cache: false,
  success: function(data) {
    $(".shopping-cart").replaceWith(data);
    //update the cart
    $(".badge").text(Object.keys(Cookies.get()).length);

    $(".button2").on("click", function(){
     alert("success"); //just a test
    });
   }
  });
 });


});

這是事件委托的一種情況:您的事件監聽器不起作用,因為在您運行該語句時沒有將其附加到.button2事件。

$(document).on("click", ".button2", function(){
    alert("success"); //just a test
});

這樣,事件在文檔級別注冊,但在.button2.button2 無論如何,使用另一個元素(可能是周圍的div)代替document作為父元素將是最佳選擇。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM