[英]How do I get a simple jQuery code to replace my current Javascript
目標:單擊導航上的鏈接時,將顯示旋轉圖像,直到腳本完全加載。
function ahah(url, target) {
document.getElementById(target).innerHTML = '<img src="loading.gif" />';
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != undefined) {
req.onreadystatechange = function() {ahahDone(url, target);};
req.open("GET", url, true);
req.send("");
}
}
function ahahDone(url, target) {
if (req.readyState == 4) { // only if req is "loaded"
if (req.status == 200) { // only if "OK"
document.getElementById(target).innerHTML = req.responseText;
} else {
document.getElementById(target).innerHTML=" AHAH Error:\n"+ req.status + "\n" +req.statusText;
}
}
}
function load(name, div) {
ahah(name,div);
return false;
}
在鏈接上
<a href="wrapper.html" onclick="load('file1.html','content');return false;">File 1</a>
<a href="wrapper.html" onclick="load('file2.html','content');return false;">File 2</a>
在內容包裝器上
<div id="content"></div>
讓我知道在 jquery 上執行此操作的簡單方法。
假設每個<a href="wrapper.html">
元素順序對應於一個file-n.html
,你可以這樣做:
$(function() {
var content = $('#content');
$('a[href="wrapper.html"]').each(function( i ) {
var name = "file" + (i + 1) + '.html';
$(this).click(function( e ) {
e.preventDefault();
content.html( '<img src="loading.gif" />' );
$.ajax({
url: name,
dataType: 'html',
success: function( data ) {
content.html( data );
},
error: function(xhr, status, error) {
content.html( "Error:\n" + status + "\n" + error;
}
});
});
});
});
當然,不要忘記首先包含 jQuery 庫。
我認為你只需要重寫'ahah'。 這是我的做法。 我還省略了您的“ahahDone”回調並將其合並到此實現中。
function ahah(url, target) {
$("#" + target).html('<img src="loading.gif" />');
$.ajax({
url: url,
type: "GET",
success: function (data, status, req) { $("#" + target).text(req.responseText); },
error: function (req, status, err) { $("#" + target).text(" AHAH Error:\n" + req.status + "\n" + req.statusText); }
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.