2013-04-30 21 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内父。