2012-10-18 30 views
0

JS:如何在外部HTML加載後觸發一個函數來執行?

$(document).ready(function(){ 

    $("#loader").load("external.html"); 

    $("#buttonClickText").live('click', function() { 
     $("#buttonClickText").text("Text changed after button click."); 
    }); 

    // MYSTERY FUNCTION 
    $("#pageLoadText").text("Text changed after external HTML was loaded."); 
    // 

}); 

外部HTML:

<div id="buttonClickText"> 
    This text changes when clicked. 
</div> 

<div id="pageLoadText"> 
    This text should have changed when external HTML was loaded, but didn't. 
</div> 

主要HTML(只顯示相關的標籤):

<div id="loader"></div> 

另外,我知道.live()已過時的jQuery 1.7+,我猜這個解決方案會使用.on()

謝謝!

回答

1

http://api.jquery.com/load/

此方法是從服務器獲取數據的最簡單的方法。它是 大致相當於$ .get(url,data,success),只是它是一個 方法而不是全局函數,並且它有一個隱式回調函數 。當檢測到成功響應時(即當textStatus 爲「成功」或「未修改」時),.load()將匹配元素的HTML內容設置爲返回的數據。

只需傳遞一個函數作爲第二個參數。

$('#result').load('ajax/test.html', function() { 
    alert('Load was performed.'); 
}); 
+0

謝謝,我知道這將是一個簡單的答案,但我無法弄清楚 –

1
下面

爲這一問題的解決方案:

$(document).ready(function(){ 
$("#loader").load("external.html", function() 
     { 
      $("#pageLoadText").text("Text changed after external HTML was loaded."); 
     } 
    ); 

$("#buttonClickText").live('click', function() { 
    $("#buttonClickText").text("Text changed after button click."); 
}); 

});

相關問題