我的代码中一直出现此错误。
Uncaught TypeError: Cannot set property 'innerHTML' of undefined
我已阅读其他一些类似错误Uncaught TypeError: Cannot set property 'innerHTML' of undefined of null
的帖子,我尝试了一些建议的方法,但似乎没有任何改变。
似乎指向这一行document.getElementsByClassName("demo")[i].innerHTML = xhttp.responseText;
我不知道为什么像之前我添加循环一样,它运行良好。
我的代码
<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<!--#include file="../Connections/DVerto.asp" -->
<%
Dim Recordset1
Dim Recordset1_cmd
Dim Recordset1_numRows
Set Recordset1_cmd = Server.CreateObject ("ADODB.Command")
Recordset1_cmd.ActiveConnection = MM_DVerto_STRING
Recordset1_cmd.CommandText = "SELECT Part_Number FROM dbo.Stock_Header WHERE Part_Number like '84%'"
Recordset1_cmd.Prepared = true
Set Recordset1 = Recordset1_cmd.Execute
Recordset1_numRows = 0
%>
<%
Dim Repeat1__numRows
Dim Repeat1__index
Repeat1__numRows = 10
Repeat1__index = 0
Recordset1_numRows = Recordset1_numRows + Repeat1__numRows
%>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body onLoad="loadDoc()">
<table width="50%" border="0" cellspacing="2" cellpadding="2">
<%
While ((Repeat1__numRows <> 0) AND (NOT Recordset1.EOF))
%>
<tr>
<td class="prodref"><%=(Recordset1.Fields.Item("Part_Number").Value)%></td>
<td class="demo"> </td>
</tr>
<%
Repeat1__index=Repeat1__index+1
Repeat1__numRows=Repeat1__numRows-1
Recordset1.MoveNext()
Wend
%>
</table>
<script>
var a = document.getElementsByClassName("prodref").length;
var i = 0;
for (i; i < a; i++) {
loadDoc();
}
function loadDoc() {
var a = document.getElementsByClassName("prodref");
a[i] = document.getElementsByClassName("prodref").innerHTML;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementsByClassName("demo")[i].innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "data.asp?prodref="+a[i].innerHTML, true);
xhttp.send();
}
</script>
</body>
</html>
<%
Recordset1.Close()
Set Recordset1 = Nothing
%>
答案 0 :(得分:1)
您正在进行异步请求,因此当调用 onreadystatechange 函数时,变量 i 将不是您所期望的。
试试这个:
...
for (i; i < a; i++) {
loadDoc(i);
}
function loadDoc(i) {
...
答案 1 :(得分:1)
您需要将i
传递给函数,因为在AJAX请求返回时循环已完成。
var prodref = document.getElementsByClassName("prodref");
var demo = document.getElementsByClassName("demo");
var i = 0;
var a = prodref.length;
for (i; i < a; i++) {
loadDoc(i);
}
function loadDoc(i) {
console.log("creating loadDoc() call for", i);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
console.log("callback invoked for", i, "with state:", xhttp.readyState);
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log("setting .innerHTML for", i, "to:", xhttp.responseText);
demo[i].innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "data.asp?prodref="+prodref[i].innerHTML, true);
xhttp.send();
}
现在i
的每个单独调用都有一个loadDoc
变量,并且您在该函数中创建的回调函数将关闭该本地i
。
这是一个闭包。
我也缓存了您的DOM选择。除非您认为它们会发生变化,否则您无需反复提取节点。