简体   繁体   English

无法设置innerHTML的属性

[英]Cannot set property of innerHTML

I have a small script which grabs a file and outputs in Javascript. 我有一个小的脚本,可以用Javascript捕获文件并输出。 Then after that output i want to edit the innerHTML. 然后在该输出之后,我要编辑innerHTML。

But its saying it cannot set it. 但是它说不能设置它。 "Uncaught TypeError: Cannot set property 'innerHTML' of null" “未捕获的TypeError:无法将属性'innerHTML'设置为null”

This is what i have: 这就是我所拥有的:

function call_file(file,div_id){

var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById(div_id).innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET",file,true);
xmlhttp.send();

}




call_file('test.php','main'); //main = div_id to display content in 
document.getElementById('total').innerHTML = 'test';

My test.php has: 我的test.php有:

<div id="total"></div>

I'm wondering why it cannot set? 我想知道为什么它不能设置?

Your call to set the innerhtml of total is happening before the state change event which happens in async. 设置total的innerhtml的调用发生在异步发生的状态更改事件之前。 You'd have to ensure your Ajax call had completed before modifying the dom based on predicted added markup. 您必须确保您的Ajax调用已完成,然后才能根据预测的添加标记修改dom。

Change second parameter of this line from 'main' to 'total', since that is the DIV, you expect the content in: 将该行的第二个参数从“ main”更改为“ total”,因为它是DIV,所以您希望其内容如下:

call_file('test.php','main'); call_file('test.php','main'); //main = div_id to display content in // main = div_id以显示内容

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

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