我有以下代码,但getElementById(setID)对我不起作用, 我知道它会捕获id,因为alert(setID)正在工作。
任何想法?
function getdata(file, aID){
req = xmlHttpRequestHandler.createXmlHttpRequest();
req.onreadystatechange = Response;
req.open("GET", file, true);
req.send(null);
setID = aID;
}
function Response() {
var ready, status;
try {
ready = req.readyState;
status = req.status;
}
catch(e) {}
if (ready == 4 && status == 200) {
document.getElementById("data").innerHTML = req.responseText;
}
document.getElementById(setID).className = "someclass";
}
<div class="msg" id="someid">
<a href="javascript:getdata('data.php', 'someid')">somelink</a>
</div>
答案 0 :(得分:4)
将setID用作全局变量或将其传递给回调函数。
function getdata(file, aID)
{
req = xmlHttpRequestHandler.createXmlHttpRequest();
setID = aID;
req.onreadystatechange = function() {Response(setID);};
req.open("GET", file, true);
req.send(null);
}
function Response(setID)
答案 1 :(得分:1)
如果
document.getElementById("data")
不起作用,在99%的情况下,这有以下原因之一:
该元素不再存在或存在
有多个ID为data
当AJAX调用引入的HTML代码也包含具有相同ID的元素时,通常会发生这种情况。
答案 2 :(得分:1)
您是否将setID
变量设为全局变量?如果没有,那么试试这个:
var setID = null; // we set this here because it is referenced in functions
function getdata(file, aID){
req = xmlHttpRequestHandler.createXmlHttpRequest();
req.onreadystatechange = Response;
req.open("GET", file, true);
req.send(null);
setID = aID;
}
function Response() {
var ready, status;
try {
ready = req.readyState;
status = req.status;
}
catch(e) {}
if (ready == 4 && status == 200) {
document.getElementById("data").innerHTML = req.responseText;
}
document.getElementById(setID).className = "someclass";
}