开发者

document.getElementById(somevar) not working

开发者 https://www.devze.com 2022-12-19 20:26 出处:网络
i have the code below but getElementById(setID) not working for me, i know it catches the id because alert(setID) working.

i have the code below but getElementById(setID) not working for me, i know it catches the id because alert(setID) working.

any idea?

function g开发者_Python百科etdata(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.

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:

  • The element does not exist or exist anymore

  • There are more than one element with the id data

This happens often when the AJAX call introduces HTML code that also contains an element with the same ID.


Are you making your setID variable global? 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";
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号