我在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
%>
答案 0 :(得分:3)
getElementsByClassName
返回节点集合,而不是单个节点。您需要迭代该集合并在每个节点上设置innerHTML
属性:
var nodes = document.getElementsByClassName("txtHint");
for (var i = 0; i < nodes.length; i++)
nodes[i].innerHTML = '';
您当前的代码是在集合本身设置属性,因为它是完全有效的JavaScript,不会出错,但也不会导致任何更新 - 现在只是节点集合有一个未使用的innerHTML
属性。
答案 1 :(得分:1)
如果查看getElementsByClassName的文档,您会注意到您正在返回一个对象数组,而getElementById会返回一个元素。
使用数组,innerHtml没有原型,只在单个元素上公开。
您需要做的是遍历从getElementsByClassName检索的元素列表。
var elements =document.getElementsByClassName("txtHint");
for(var i = 0; i < elements.length; i++){
elements[i].innerHTML = xhttp.responseText
};
试一试,看看是否有帮助