2011-07-09 33 views
6

檢查jQuery源代碼後,我看到我遇到的問題是因爲replaceWith調用html,這對XML文檔不存在。 replaceWith不應該在XML文檔上工作嗎?replaceWith on XML問題

我發現這固然簡單的解決方法,如果有人需要它在未來,這將完成我想要做的事:

xml.find('b').each(function() { 
    $(this).replaceWith($('<c>yo</c>')) // this way you can custom taylor the XML based on each node's attributes and such 
}); 

但我還是想知道爲什麼簡單的方法不起作用。


我對jQuery瞭解不多,但是不應該這樣工作嗎?

xml = $.parseXML('<a><b>hey</b></a>') 
$(xml).find('b').replaceWith('<c>yo</c>') 

而不是xml代表<a><c>yo</c></a>失敗,代表<a></a>。我做錯什麼了嗎?我正在使用jQuery 1.6.2。

編輯:

作爲一個方面說明,如果我嘗試使用replaceWith功能版本,就像這樣:

$(xml).find('b').replaceWith(function() { 
    return '<c>yo</c>' // doesn't matter what I return here 
}) 

我得到這個錯誤:

TypeError: Cannot call method 'replace' of undefined 

編輯2:

replaceAll不過工作,但我需要使用功能版本,所以我不能滿足於這一點:

$('<c>yo</c>').replaceAll($(xml).find('b')) // works 

編輯3:

這也適用於:

xml.find('b').replaceWith($('<c>yo</c>')) // but not with the $() around the argument 

回答

2

這看起來像是一個設計限制replaceWith()或一個錯誤。

當我運行:

$(xml).find('b').replaceWith(function() { 
    return '<c>yo</c>'; 
}) 

我得到了"this[0].innerHTML is undefined"例外。 See this jsFiddle

鑽入xmlb節點沒有innerHTML成員 - 這有一定意義,因爲它不是HTML。 ;)

因此,它看起來像replaceWith()可能不總是與XML很好玩。 Consider reporting a bug

+0

你認爲這值得報告嗎? –

+0

@Seth:當然,爲什麼不呢?最糟糕的情況是你會得到一個「不會修復」的問題,至少這個問題會被記錄下來。 –

+0

是的。它不像合理的人們所期望的那樣工作,或者正如文件所暗示的那樣。只需在發佈之前搜索以前的錯誤(我做了*快速*搜索並沒有看到任何內容)。 –

0

是的。這是舊的bug,它仍然存在。你可以解決它:

$.ajax 
    dataType: "xml" 
    ... 
    success: (data) -> 
    $(data).find("section").each -> 
     ugly_but_working_clone = $($(".existing_dom_element").append(this).html())