使用jQuery将元素添加到具有唯一id的div中的另一个div中

3
我想将某些元素附加到具有唯一id的另一个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 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);
});

请注意,唯一标识符(ID)必须以字母开头。ID和名称标记必须以字母([A-Za-z])开头,并可以跟随任意数量的字母、数字([0-9])、连字符("-")、下划线("_")、冒号(":")和句点(".")...但浏览器非常宽容 ;) - SirDerpington
如果我理解你的问题正确:appendTo("#" + stopId + " > .ui-collapsible-content"); - Mahn
2
@SirDerpington,对于HTML5不是这种情况。 - billyonecan
@billyonecan 你是对的!我很抱歉。 - SirDerpington
3个回答

3

使用 .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);
});

1

我不完全确定你为什么要使用("#" + stopId)。将stopId设置为父div而不仅仅是id更有意义。当你添加时,可以使用$('child', 'parent')设置选择器所在的上下文。所以你可以这样做...

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

基本上,这会在父级中查找 .ui-collapsible-content。

0

试试这个

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

1
我会使用.children而不是.find - Pete

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接