2010-07-23 65 views
1

我想知道是否有人知道更好的方式來寫這段代碼。縮短jQuery命令

if($('div.homeBox > div').length > 0){ 
    $('div.homeBox > div').remove(); 
} 
$('div.homeBox').append(data.loadPage); 

這樣工作,但我想盡可能使它漂亮。我使用ajax請求(data.loadPage)返回的HTML數據替換了我的頁面中的一段代碼。

data.loadPage的一個例子是提前任何建議

<div id="variousIDs" > 
    ... some content ... 
</div > 

感謝。

+1

爲什麼測試'length> 0'?對一組空的結果調用'.remove()'應該什麼都不做。 – Lucas 2010-07-23 17:30:53

回答

1
// you don't need to test if it exists first 
$('div.homeBox > div').remove() 
$('div.homeBox').append(data.loadPage); 

// if you want to do it in one go, this less clear option should work, too: 
// .end() moves back up the stack to undo the last filter operation (.children()) 
$('div.homeBox').children('div').remove().end().append(data.loadPage); 

// if you want to get rid of everything within homebox, this is even easier: 
$('div.homeBox').empty().append(data.loadPage); 
+0

這正是我正在尋找的,感謝您的快速回復。 – stmpy 2010-07-23 17:44:00

0

給了DIV中div.homeBox自己的ID(例如, 「ID = homeBoxInnerDiv」 或東西),然後

如果($( '#homeBoxInnerDiv')。可見()){
$( '#homeBoxInnerDiv')replaceWith(data.loadPage)。
}

這將替換您想要使用新內容刪除的div的內容。