2012-12-19 20 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元素。