我有這樣的代碼:for循環,這並不需要運行
<script type="text/javascript">
var url = "http://www.xxxxx.xxx/xxxxxxxxx";
var txt;
var id1;
var id2;
var imgarres = [];
var imgarr = [];
var imgels = [];
function getdata() {
if (id1){clearTimeout(id1);}
if (id2){clearTimeout(id2);}
var xhr = new XMLHttpRequest();
xhr.open('GET',url, true);
xhr.setRequestHeader('Cache-Control', 'no-cache');
xhr.setRequestHeader('Pragma', 'no-cache');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
txt = xhr.responseText;
var r = txt.indexOf('<b class="fl_r">Online</b>');
var el = document.createElement("div");
el.innerHTML = txt;
var n = imgprocess(el);
var nam = el.getElementsByTagName("title")[0].innerHTML;
if (r != -1) {
var notification = webkitNotifications.createNotification('plus.gif', nam, 'online!!');
notification.show();
var id1 = setTimeout(getdata, 60000);
} else {
var notification = webkitNotifications.createNotification(n, nam, 'offline!!');
notification.show();
var id2 = setTimeout(getdata, 600000);
}
}
}
xhr.send();
}
function imgprocess(text) {
imgels = text.getElementsByTagName("IMG");
for (var i=0;i< imgels.length;i++) {
if (imgels[i].src.indexOf(parse(url)) != -1) {
imgarr = imgels[i];
}
}
for (var p=0; p< imgarr.length; p++) {
if (imgarr[p].parentNode.nodeName=="A") {
imgarres = imgarr[p];
}
}
var z = imgarres[0].src;
return z;
}
function init() {
getdata();
}
</script>
</head>
<body onload="init();">
當我執行這個代碼,錯誤說:「SRC無法讀取的未定義」關於var z = imgarres[0].src;
當我從那條線,擴建工程中刪除src
沒有錯誤,但 imgprocess
例程不會返回期望值!預期值是imgurl,這是我刪除的src。看起來第二個循環(for (var p=0; p< imgarr.length; p++){
)根本沒有運行,但第一個是OK。我該如何解決?
P.S .:我試着像這樣傳遞迴調:xhr.onreadystatechange = function(imgprocess) {
但它不起作用。它表示「未捕獲的typeerror」對象不是函數。
你是什麼意思?我首先檢查與console.log(imgarr)循環;第一個for循環很好.. – DrStrangeLove
我添加了一些解釋並解釋了爲什麼第二個循環是錯誤的。 – lmz
那麼爲什麼console.log(imgarr)輸出我需要的img元素? – DrStrangeLove