2014-10-02 51 views
0

我拉通過AJAX的XML文檔,並試圖插入一個新的節點在文檔的頂部,但我得到一個新的節點插入上面的每個匹配的子節點。我以爲通過使用.children(0)我只會做一次。jQuery Children之前的語法問題

我的錯誤是什麼?

$.ajax({ 
    type: "GET", 
    url: fileUrl, 
    dataType: "xml", 
    success: parseResultsXML 
}); 
function parseResultsXML(xml) { 
    $(xml).children(0).children(0).before("<item>New Node</item> \n"); 
    var xmlOutput = new XMLSerializer().serializeToString(xml); 
    console.log(newfile, xmlOutput); 
} 

//Original File 
<?xml version="1.0" encoding="UTF-8"?> 
<items> 
    <item>Existing Node 1</item> 
    <item>Existing Node 2</item> 
</items> 

//Expected Output 
<?xml version="1.0" encoding="UTF-8"?> 
<items> 
    <item>New Node</item> 
    <item>Existing Node 1</item> 
    <item>Existing Node 2</item> 
</items> 

//Actual Output 
<items> 
    <item>New Node</item> 
    <item>Existing Node 1</item> 
    <item>New Node</item> 
    <item>Existing Node 2</item> 
</items> 
+0

[.children()](http://api.jquery.com/children/)可選接受選擇器作爲參數,但不接受索引。使用'.children(':first')'或'.children()。eq(0)'。 – Regent 2014-10-02 17:31:28

+0

.eq(0)做到了。想提交答案嗎? – Wesley 2014-10-02 17:33:14

+0

如果你認爲它應該是答案 - 那麼是的:) – Regent 2014-10-02 17:35:28

回答

1

.children()可選地接受selector作爲參數,但不是索引。您可以使用.children(':first').children().eq(0)

JSFiddle example

<div> 
    <span>first</span> 
    <span>second</span> 
</div> 

console.log($('div').children().eq(0).text()); 
console.log($('div').children(':first').text());