DIV CSS 佈局教程網

jQuery 的 load() 方法與回呼函數用法範例
編輯:JQuery特效代碼     

本文示範 jQuery 的 load() 方法,並說明如何搭配回呼函數(callback)掌握載入結果。

下面的程式碼示範了 load() 的基本用法,以及帶回呼函數的進階用法:

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("#div1").load("demo_test.txt", function(responseTxt, statusTxt, xhr){
      if(statusTxt == "success") alert("External content loaded successfully!");
      if(statusTxt == "error") alert("Error: " + xhr.status + ": " + xhr.statusText);
    });
  });
});
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>
</body>
</html>

load() 會把外部檔案的內容直接塞進指定元素中;若加上回呼函數,就能透過 statusTxt 判斷載入成功或失敗,並以 xhr 取得錯誤狀態碼,便於除錯與提示。希望本文對大家的 jQuery 開發有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved