2013-01-31 82 views
1

我遇到了類似如下的問題:JavaScript not working inside AJAX loaded DIV但我的問題是我沒有任何綁定的事件。我有這個:JQuery ToolTip在AJAX調用後不工作

$('[title]').colorTip({color:'yellow'}); 

將'title'屬性的所有元素綁定到該對象。它在頁面重新加載時工作正常。但是,從AJAX調用的元素的故事是不同的,它顯示像JavaScript不存在。我知道使用live()將元素綁定到來自AJAX的其他事件,但是如何綁定沒有「事件」的元素?

回答

9

您必須在ajax調用後重新綁定工具提示。

$(document).ajaxStop(function() { 
    $('[title]').colorTip({color:'yellow'}); 
}); 

或者通過jbabey的建議,您可以使用完整的回調來重新綁定提示(從​​here的簡化版本):

$(
function(){ 
    // Get a reference to the content div (into which we will load content). 
    var jContent = $("#content");    
    // Hook up link click events to load content. 
    $("a").click(
     function(objEvent){ 
      var jLink = $(this); 
      // Clear status list. 
      $("#ajax-status").empty(); 
      // Launch AJAX request. 
      $.ajax(
       { 
        // The link we are accessing. 
        url: jLink.attr("href"), 
        // The type of request. 
        type: "get", 
        // The type of data that is getting returned. 
        dataType: "html", 
        complete: function(){ 
         console.log("finalized ajax request"); 
         //re-bind the tooltip 
         $('[title]').colorTip({color:'yellow'}); 
        }, 
        success: function(strData){ 
         console.log("ajax success"); 
         console.log(strData); 
         // to something with the received data 
         jContent.html(strData); 
        } 
       }       
       ); 
      // Prevent default click. 
      return(false);      
     } 
     ); 

} 
); 

基於您的評論我包括以下內容:你也必須確保您在頁面加載時綁定工具提示:

$(document).ready(function() { 
    $('[title]').colorTip({color:'yellow'}); 
}); 
+0

它可能會更好地把它放在'完成'回調,除非他有多個Ajax調用操縱dom。 – jbabey

+0

你說得對。我將你的建議包括在我的答案中。 –

+0

這解決了Ajax調用的問題...但是後來出現了問題,因爲我不得不作出Ajax調用,即使對第一次加載頁面的元素也要這樣。 – IROEGBU

0

您可以在元素上創建更改事件。

$('title').live('change', function() { 
whatever you want to do here 
}) 

然後,只要希望屬性生效,就可以觸發更改。

$('title').trigger('change'); 
+3

-1 .live()從版本1.7開始已被棄用。 .on是替代品,應該繼續使用。 – bpeterson76