我一直在编写这段代码,以便从通过AJAX检索的XML文档动态加载照片链接。我有一个存储响应XML的全局变量xDoc,我在其他函数中使用它,这样我就不必每次都加载文档。请记住,我对JavaScript相当陌生,所以细节将是伟大的。
我得到这个错误在Chrome: "未捕获的TypeError:不能调用方法'getElementsByTagName'未定义",并在其他浏览器中类似的错误消息。但是,我的代码仍然可以在FireFox、Chrome和Safari中工作。然而,当涉及到IE时,每个版本都无法正常工作。我不明白哪里出了问题,为什么元素没有定义。
错误行在下面的代码中被清楚地标记出来。这是"eProject"。link = eProject.photo.getElementsByTagName("edit")[0].firstChild.data;"
我的XML的数据结构如下:
<project>
<stuff>
<stuff>
<photos>
<photo>
<stuff>
<edit>
</photo>
</photos>
</project>
然后是JavaScript:
// Initialize
function init() {
// Set the xml file
loadXMLDoc("../xml/featured.xml");
}
window.onload = init;
// Define xDoc global variable
var xDoc;
var proImages = new Array();
// Retrieve XML document as document object
function loadXMLDoc(url) {
var req = null;
try {
req = new XMLHttpRequest();
req.overrideMimeType("text/xml");
}
catch(e) {
req = null;
}
if (req) {
xDoc = null;
req.open("GET", url, true);
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
xDoc = req.responseXML;
if (xDoc && typeof xDoc.childNodes != "undefined" && xDoc.childNodes.length == 0) {
xDoc = null;
}
else {
eProject = xDoc.getElementsByTagName("project")[0];
eProject.id = eProject.getElementsByTagName("id")[0].firstChild.data;
getProject(eProject.id);
}
}
}
}
req.send(null);
}
}
function getProject(id) {
count = xDoc.childNodes.length;
i = 0;
for (i; count; i = i + 1) {
eProject = xDoc.getElementsByTagName("project")[i];
eProject.id = eProject.getElementsByTagName("id")[0].firstChild.data;
if (eProject.id == id) {
// Remove old numbers
cImages = document.getElementById("cImages");
if (cImages.firstChild) {
while (cImages.firstChild)
{
cImages.removeChild(cImages.firstChild);
}
}
// Reset Array
proImages.length = 0;
eProject.photos = eProject.getElementsByTagName("photos")[0];
eProject.phot = eProject.photos.getElementsByTagName("photo");
pCount = eProject.phot.length;
i = 0;
for (i; pCount; i = i + 1) {
/*
* THIS IS WHERE THE ERROR IS
*/
eProject.photo = eProject.phot[i];
// This is the line of code that generates the error message
eProject.link = eProject.photo.getElementsByTagName("edit")[0].firstChild.data;
proImages[i] = eProject.link;
dynamImg = document.getElementById('dynamImg');
dynamImg.src = proImages[0];
dynamImg.setAttribute('onclick', 'getNumImg(1)');
nButton = document.createElement('button');
nButtonTxt = document.createTextNode(i + 1);
nButton.appendChild(nButtonTxt);
nButton.type = "button";
nButton.value = i;
if (nButton.value == '0') {
nButton.setAttribute('id', 'nButtonSelect');
}
nButton.setAttribute('onclick', 'getNumImg(' + i + ')');
cImages.appendChild(nButton);
}
break;
}
}
}
我是否正确,你有两个循环,一个在另一个里面,在这两个你使用" I "变量作为迭代器?你不应该在第二个循环中使用"j"吗?
我想你想要这个在你的for循环for (i; i < pCount; i = i + 1) {
(注意i <
) -否则它只是检查,看看pCount是否被定义,并将无限期地运行。我怀疑当i
比eProject.phot
中的元素数量更大时,eProject.photo
将是未定义的。
var t = quotes[i].getElementsByTagName("t")[0].childNodes[0].nodeValue;