duanan5940 2015-10-06 02:11
浏览 1631
已采纳

由于某种原因,document.getElementById()。innerHTML不起作用?

i have a span with the same value..

echo "<span id='msgNotif1' class='badge'  style='position:relative;right:5px;bottom:10px;'>".$number."</span>"; 

where $number have a value..

and my js code is..

var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                var val = xmlhttp.responseText;
                //alert(val);
                document.getElementById("msgNotif1").innerHTML = val;
                //document.getElementById("msgNotif2").innerHTML = val;
                alert(val);
                //document.getElementById("msgNotif3").innerHTML = xmlhttp.responseText;    
            }
        }
        xmlhttp.open("GET", "some page", true);
        xmlhttp.send();

the problem is the value still remains and do not change, trying to uncomment the first alert shows an alert with the right value, but when i try to comment it the second alert never executed, giving me an idea that the document.getelementbyid().innerhtml is the one that is not working, been with this for a few hours, any help will be appreciated. thanks in advance

  • 写回答

2条回答 默认 最新

  • drap5081683 2015-10-06 02:19
    关注

    Your error message Cannot set property 'innerHTML' of null" means that:

    document.getElementById("msgNotif1")
    

    is returning null. That can happen for several possible reasons:

    1. There is no element in your page with id="msgNotif1".
    2. You are calling this code before your document has finished loading and thus the element with id="msgNotif1" has not yet loaded. This can commonly happen if you execute your code in the <head> section of the document rather than at the very end of <body> or in response to the DOMContentLoaded event.
    3. Your content is dynamically loaded (not in the original page HTML) and you are calling document.getElementById("msgNotif1") before your dynamic content has been loaded.
    4. You have some HTML errors which are preventing the proper parsing of your HTML that contains the element with id="msgNotif1".

    For a general purpose description of how to run Javascript after the current page has been loaded without using a framework like jQuery, see this answer: pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭