在w3Data library負載定義的內容異步函數w3IncludeHTML
。它提供了當它已經完成它的工作得到通知沒辦法:
function w3IncludeHTML() {
var z, i, a, file, xhttp;
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
if (z[i].getAttribute("w3-include-html")) {
a = z[i].cloneNode(false);
file = z[i].getAttribute("w3-include-html");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
a.removeAttribute("w3-include-html");
a.innerHTML = xhttp.responseText;
z[i].parentNode.replaceChild(a, z[i]);
w3IncludeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
return;
}
}
}
一個快速的解決辦法是改變上述功能,下面的代碼添加到您的腳本:
function w3IncludeHTML(callback) {
var z, i, file, xhttp;
z = document.querySelector("[w3-include-html]");
if (!z) {
// notify caller that all is loaded
if (callback) callback();
return;
}
file = z.getAttribute("w3-include-html");
z.removeAttribute("w3-include-html");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4) {
if (xhttp.status == 200) {
z.innerHTML = xhttp.responseText;
}
w3IncludeHTML(callback);
}
}
xhttp.open("GET", file, true);
xhttp.send();
}
該版本將覆蓋w3Data庫提供的功能,並對其進行改進。現在,您可以通過一個回調函數來w3IncludeHTML
,在其中您可以肯定,所有內容都加載(除非錯誤發生,當然):
$(document).ready(function() {
w3IncludeHTML(function() {
// Everything that depends on loaded content, should be done here:
lastpath=(window.location.pathname).split("/").slice(-1).pop();
// not needed: alert(lastpath);
$('a[href$="'+lastpath+'"]').attr("class","selected");
$('a[href$="'+lastpath+'"]').parent(".dropdown-content").prev().attr("class","selected");
});
});
是否'w3IncludeHTML()'執行任何異步操作? – Barmar
爲了測試,'$('a [href $ =''+ lastpath +'「]')'(或'$('a [href $ =''+ lastpath +'」]')。parent(「。dropdown -content「).prev()')在警報之前存在? – apsillers
9/10次,警報只是購買腳本加載的時間 – dandavis