2013-04-30 59 views
2

我想追加某些元素到另一個div內的div與唯一的編號。jQuery appendTo div與唯一編號的div內

<div data-role="collapsible" id="49617" class="ui-collapsible ui-collapsible-inset ui-corner-all"> 
    <h2 class="ui-collapsible-heading"> 
    </h2> 
    <div class="ui-collapsible-content" aria-hidden="false"></div> 
</div> 

父DIV data-role="collapsible"有一個id這是動態的。子div div ui-collapsible-content由我正在使用的框架創建。如何通過點擊按鈕將元素添加到此div中。

這是我的jQuery代碼如下,變量stopId是父div的id。它附加到父div,但不添加到所需的子div。

$("<h2 />").text("Buses Due").appendTo("#" + stopId); 

$.each(data.arrivals, function(i,item){ 

    $("<span/>") 
    .text(item.estimatedWait) 
    .attr("class", "busListing time") 
    .appendTo("#" + stopId); 

    $("<span/>") 
    .text(item.routeName + ' to ' + item.destination) 
    .attr("class", "busListing info") 
    .appendTo("#" + stopId); 

    $("<br/>") 
    .appendTo("#" + stopId); 
}); 
+0

小心。唯一的標識符(ID)必須以字母開頭。 ID和名稱標記必須以字母([A-Za-z])開頭,後面可以跟隨任意數量的字母,數字([0-9]),連字符(「 - 」),下劃線(「_」) ,冒號(「:」)和句點(「。」)...但瀏覽器非常寬容;) – SirDerpington 2013-04-30 14:15:14

+0

如果我正確理解你在問什麼:'appendTo(「#」+ stopId +「> .ui-collapsible ';' – Mahn 2013-04-30 14:17:33

+2

@SirDerpington那不適用於HTML5 – billyonecan 2013-04-30 14:18:34

回答

2

使用.appendTo("#" + stopId + ' > .ui-collapsible-content')

例:

$("<h2 />").text("Buses Due").appendTo("#" + stopId); 

var el = $("#" + stopId).children('.ui-collapsible-content'); 
$.each(data.arrivals, function(i,item){ 

    $("<span/>") 
    .text(item.estimatedWait) 
    .attr("class", "busListing time") 
    .appendTo(el); 

    $("<span/>") 
    .text(item.routeName + ' to ' + item.destination) 
    .attr("class", "busListing info") 
    .appendTo(el); 

    $("<br/>") 
    .appendTo(el); 
}); 
+0

感謝作品像一個魅力。 – Emmanuel 2013-04-30 14:28:03

0

試試這個

.appendTo($("#" + stopId).children('ui-collapsible-content')); 
+1

我會使用'.children'而不是'.find' – Pete 2013-04-30 14:19:44

1

我不能完全肯定,爲什麼你使用的( 「#」 + stopId)。只需將stopId設置爲父div,而不僅僅是id,就更有意義。追加時,可以使用$('child','parent')設置選擇器的上下文。所以你會做類似的東西...

.appendTo('.ui-collapsible-content', parentDiv); // parentDiv = "#" + stopId 

基本上,這發現.ui-collapsible-content內父。