我正在使用jQuery在项目中操纵dom。我有类似的类方法:
<!-- 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);
}
此方法的第一个调用中的一切都可以,因为它会创建节点并将其附加到父节点。第二个调用(使用replaceWith()
方法)也可以正常工作。但是之后,属性 this._BlockNode[0].parentNode
为null。因此,当我称其为第三次时,replaceWith()
与没有.parentNode
属性的新_.BlockNode
一起使用时,它不会替换节点的内容,因为此检查:if ( !isDisconnected( this[0] ) ) { //line 5910 in jQuery 1.8.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;
it May 最好将本机元素保存在_BlockNode
而不是jQuery对象中。