簡體   English   中英

Ajax 調用后 Jquery 函數不起作用

[英]Jquery function doesn't work after Ajax call

我有這個功能:

$(document).ready(function() {
$('.post_button, .btn_favorite').click(function() {


//Fade in the Popup
$('.login_modal_message').fadeIn(500);

// Add the mask to body
$('body').append('<div class="overlay"></div>');
$('.overlay').fadeIn(300);  
return false;
});

我的頁面使用收藏夾按鈕加載內容,但在 Ajax 調用並生成其他新內容后,當您單擊新內容的按鈕時,該功能不起作用。 什么可能不正確?

那是因為您正在使用動態內容。

您需要在點擊通話改為像一個委托的方法on

$('.post_button, .btn_favorite').on('click', function() {

$("body").on( "click", ".post_button, .btn_favorite", function( event ) {

取而代之的是:

$('.post_button, .btn_favorite').click(function() {

這樣做:

$(document).on('click','.post_button, .btn_favorite', function() {

on將與匹配選擇器的當前元素和未來元素一起使用。

干杯

class-of-elementclass-of-element的應用類。 這是這里的選擇器。

  $(document).on("click", ".class-of-element", function (){
    alert("Success");
  });

我不確定我是否正確回答了您的問題,但您可能想嘗試..

$.ajax({
  url: "test.html"
}).done(function() {
   $('.post_button, .btn_favorite').click(function() {


    //Fade in the Popup
    $('.login_modal_message').fadeIn(500);

   // Add the mask to body
   $('body').append('<div class="overlay"></div>');
   $('.overlay').fadeIn(300);  
   return false;
});

只需嘗試將您的代碼粘貼到done函數中。

希望能幫助到你 :)

編輯:我也注意到你不見了}); 關於你的問題。

如果您知道 .post_button、.btn_favorite 的容器,則使用

$('#container_id').on('click', '.post_button, .btn_favorite', function () { });

因此,如果未找到'.post_button, .btn_favorite'則它將冒泡到container_id

否則,如果您不知道容器,則將其委托給文檔

$(document).on('click', '.post_button, .btn_favorite', function () { });

參考

以下對我有用

    $(document).ready(function(){ 
         $(document).bind('contextmenu', function(e) {
            if( e.button == 2 && jQuery(e.target).is('img')) {
              alert('These photos are copyrighted by the owner. \nAll rights reserved. \nUnauthorized use prohibited.'); 
              return false;
            }
         });
    });

一旦您的ajax內容被替換為舊內容,您需要綁定jQuery點擊事件

在 AJAX 成功塊中,您需要添加像這里的代碼新響應 html 內容一個標簽

<a href="#" id="new-tag">Click Me</a>

因此您可以在更改內容后使用以下代碼綁定新的點擊事件

$("#new-tag").click(function(){
   alert("hi");
   return false;
});

暫無
暫無

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

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