このコードを書いて、AJAXで取得したXML文書から写真リンクを動的に読み込みました。私はレスポンスXMLを格納するグローバルvaribale xDocを持っており、毎回ドキュメントをロードする必要がないように他の関数で使用しています。私はJavaScriptをかなり新しくしているので、詳細は素晴らしいと思います。JavaScript getElementsByTagName()未定義、IE失敗、AJAX XMLファイル
「Uncaught TypeError:未定義のメソッド 'getElementsByTagName'を呼び出すことができません。他のブラウザでも同様のエラーメッセージが表示されます。しかし、私のコードはFireFox、Chrome、Safariで動作します。しかし、IEに関しては、すべてのバージョンが動作しません。私は何が間違っているのか、なぜ要素が定義されていないのか理解できません。
エラーコードは、以下のコードではっきりとマークされています。これは "eProject.link = eProject.photo.getElementsByTagName(" edit ")[0] .firstChild.data;"
<project>
<stuff>
<stuff>
<photos>
<photo>
<stuff>
<edit>
</photo>
</photos>
</project>
が、これはJavaScriptのである:次のように
私のXMLのデータ構造である
// 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;
}
}
}
これは、jQueryのようなものを使用する方がはるかに簡単です。 – Dutchie432
XMLをどのように初期化したのかを追加しました –