【问题标题】:javascript insertBefore method results to "NotFoundError: An attempt was made to reference a Node in a context where it does not exist."javascript insertBefore 方法导致“NotFoundError:尝试在不存在的上下文中引用节点。”
【发布时间】:2013-12-18 12:49:30
【问题描述】:

这是我的html:

<html><body>
page starts here
this is a test page
top:
<script id="invoc_code" type="text/javascript">
    window.onload = function() {
        var xhr;
        if (window.XMLHttpRequest) {
            xhr = new XMLHttpRequest();
        } else {
           xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xhr.onreadystatechange = function() {
            var body = document.body;                                       
            if (xhr.readyState == 4 && xhr.status == 200) {
                if(body.firstChild){
                    body.insertBefore(xhr.response, body.firstChild);
                } else {
                    body.appendChild(xhr.response);
                }
            }
       };
       xhr.open("GET", "http://google.com", true);
       xhr.send(); 
    };
</script>;

page ends here
</body></html>

body.insertBefore(xhr.response, body.firstChild); 行导致“NotFoundError:尝试在不存在的上下文中引用节点”。你能告诉我是什么原因吗?

提前致谢

【问题讨论】:

  • 您只能将 DOMNodes 插入 DOM。我怀疑xhr.response 是一个。
  • 我猜,body没有任何子节点
  • 正确的 Marcell Fulop,谢谢:)
  • anand4tech ,有文本节点作为body的子节点。

标签: javascript


【解决方案1】:

insertBefore 方法需要一个 DOM 元素作为其第一个参数。如果 XHR 响应是一个 HTML 字符串,那么您需要使用它创建一个。根据您所需的 DOM 输出,您可以执行以下操作:

var newElem = document.createElement("div");
newElem.innerHTML = xhr.response;
body.insertBefore(newElem, body.firstChild);

【讨论】:

  • 对。非常感谢:)
猜你喜欢
  • 2013-11-04
  • 2014-02-17
  • 1970-01-01
  • 1970-01-01
  • 2019-03-03
  • 1970-01-01
  • 2022-11-30
  • 1970-01-01
  • 2020-02-07
相关资源
最近更新 更多