JavaScript,innerHTML无法被javascript识别

时间:2011-10-29 08:35:56

标签: javascript

我的网站有以下代码: -

function HCreateWindow(top,left,width,height,zindex,parent) {
var handle = Math.floor(Math.random()*10000000000);

if(parent==null) {
document.write("<div id=\"HWINDOW" + handle + "\"style=\"top: " + top + "px; left: " + left + "px;width: " + width + "px;height: " + height + "px; border: 1px solid black;z-index: " +zindex +"\" class=\"drag\"></div>");
} else {
    document.getElementById("HWINDOW" + parent).innerHTML += "<div id=\"HWINDOW" + handle + "\"style=\"top: " + top + "px; left: " + left + "px;width: " + width + "px;height: " + height + "px; border: 1px solid black;z-index: " +zindex +"\" class=\"drag\"></div>";
}
return handle;
}

事实证明,innerHTML使Internet Explorer 8说innerHTML是null或不是对象。认为这可能是IE的错误我更新到IE9。还是有同样的问题。但是,如果我在'if'之前添加行: -

document.write(parent);

它有效,就像识别innerHTML一样。不知道这两个命令是如何相关的。唯一的问题是我不想显示“父”的内容,因为这会使网页不整洁。有线索吗?

1 个答案:

答案 0 :(得分:1)

假设你在document.write和父节点存在之后将其称为内联(变量名称不佳)它应该可以工作

function HCreateWindow(top,left,width,height,zindex,parentIdent) {
  var handle = Math.floor(Math.random()*10000000000);
  var html = '<div id="HWINDOW' + handle + '"style="top:' + top + 'px; left:' + left + 'px;width:' + width + 'px;height:' + height + 'px; border:1px solid black;z-index:' +zindex +'" class="drag"></div>';
  if (parentIdent==null) {
    document.write(html); 
  } 
else {
    document.getElementById("HWINDOW" + parentIdent).innerHTML = html;
  }
  return handle;
}

所以

<script>
var hnd = HCreateWindow(10,100,200,400,1000);
</script>

OR

<div id="HWINDOWxxx"></div>

<script>
var hnd = HCreateWindow(10,100,200,400,1000."xxx");
</script>