简体   繁体   English

document.getElementById(somevar)无法正常工作

[英]document.getElementById(somevar) not working

i have the code below but getElementById(setID) not working for me, i know it catches the id because alert(setID) working. 我有下面的代码,但getElementById(setID)对我不起作用,我知道它捕获了ID,因为alert(setID)有效。

any idea? 任何想法?

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>

Either use setID as a global variable or pass it to the callback function. 将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) 

If 如果

document.getElementById("data")

doesn't work, this has one of the following reasons in 99% of all cases: 不起作用,这是以下原因之一,占所有案例的99%:

  • The element does not exist or exist anymore 元素不存在或不再存在

  • There are more than one element with the id data id data有多个元素

This happens often when the AJAX call introduces HTML code that also contains an element with the same ID. 当AJAX调用引入HTML代码(其中也包含具有相同ID的元素)时,通常会发生这种情况。

Are you making your setID variable global? 您是将setID变量setID全局变量吗? If not then try this: 如果没有,请尝试以下操作:

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";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM