2012-12-19 21 views
2

我正在使用jQuery来操作我的项目中的DOM。我有类方法,即是这样工作的:replaceWith jQuery方法后,父节点为null

<!-- language: lang-js -->  
var template = this._Template.split('{0}'); 
    var content = template[0] + this._Content + template[1]; 
    if (!this._BlockNode) { 
     this._BlockNode = $(content); 
     this._ParentNode.append(this._BlockNode); 
    } 
    else { 
     this._BlockNode.replaceWith(content); 
    } 

一切都是这种方法的第一个呼叫OK,因为它创建节点,并将其追加到父节点。第二个电话(使用replaceWith()方法)也可以。但是之后它的属性this._BlockNode[0].parentNode为空。因此,当我第三次打电话时,replaceWith()与新的_.BlockNode一起使用,而不使用.parentNode属性,因此此检查不会替换节点的内容:if (!isDisconnected(this[0])) { //line 5910 in jQuery 1.8.3
如何处理?

回答

3

您需要确保_BlockNode始终指向当前的版本的内容。

当您调用replaceWith时,您正确地更新了DOM结构,但未能更新对象的内容。最初的_BlockNode最终成为孤立,并且所有后续的replaceWith调用都在该节点上工作,而不是在较新的内容上工作。

尝试这种情况:

var template = this._Template.split('{0}'); 
var $content = $(template[0] + this._Content + template[1]); 
if (!this._BlockNode) { 
    this._ParentNode.append($content); 
} else { 
    this._BlockNode.replaceWith($content); 
} 
this._BlockNode = $content; 

可以优选在_BlockNode而非jQuery对象以保持天然DOM元素。