![](/img/trans.png)
[英]Ajax document.getElementById in innerHTML doesn't work
[英]Ajax doesn't work when I change document.getElementById
我有以下代碼,這些代碼是我在W3Schools上找到的,當我使用document.getElementById
它可以工作,當我將其更改為document.getElementsByClassName
(在我的完整代碼中,我將不只是<p class="txthint">
我應該使用documents.getElementsByClassName
),它只是停止工作。
<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<!--#include file="Connections/PSCRM.asp" -->
<%
Dim Recordset1
Dim Recordset1_cmd
Dim Recordset1_numRows
Set Recordset1_cmd = Server.CreateObject ("ADODB.Command")
Recordset1_cmd.ActiveConnection = MM_PSCRM_STRING
Recordset1_cmd.CommandText = "SELECT prodref FROM dba.proditem where created >= '2015-08-01' and obsolete = '0' ORDER BY prodref asc"
Recordset1_cmd.Prepared = true
Set Recordset1 = Recordset1_cmd.Execute
Recordset1_numRows = 0
%>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form action="">
<input type="text" onChange="showCustomer(this.value)" value="">
</form>
<br>
<div class="txtHint">Customer info will be listed here...</div>
<script>
function showCustomer(str) {
var xhttp;
if (str == "") {
document.getElementsByClassName("txtHint").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementsByClassName("txtHint").innerHTML = xhttp.responseText;
}
}
xhttp.open("GET", "data.asp?prodref="+str, true);
xhttp.send();
}
</script>
</body>
</html>
<%
Recordset1.Close()
Set Recordset1 = Nothing
%>
getElementsByClassName
返回節點的集合,而不是單個節點。 您需要迭代該集合並在每個節點上設置innerHTML
屬性:
var nodes = document.getElementsByClassName("txtHint");
for (var i = 0; i < nodes.length; i++)
nodes[i].innerHTML = '';
您當前的代碼是在集合本身上設置屬性,因為它是完全有效的JavaScript,不會出錯,但是也不會導致任何更新-只是現在節點集合具有未使用的innerHTML
屬性。
如果查看getElementsByClassName的文檔,則會注意到您正在返回一個對象數組,而getElementById返回一個元素。
對於數組,innerHtml沒有原型,它僅在單個元素上公開。
您需要做的是遍歷從getElementsByClassName中檢索到的元素列表。
var elements =document.getElementsByClassName("txtHint");
for(var i = 0; i < elements.length; i++){
elements[i].innerHTML = xhttp.responseText
};
試試看,看看是否有幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.