【问题标题】:Append element from another page?从另一个页面附加元素?
【发布时间】:2017-12-12 02:02:30
【问题描述】:

鉴于此 HTML:

index.html:

<div class="tile" data-tilename="test">
    <div class="tileHeader">Tile Name</div>
</div>

平铺内容.html:

<div id="test-tile" class="tileContent">
       <!-- lots of stuff here. -->
</div>

我怎样才能得出以下结论?

<div class="tile">
    <div class="tileHeader">Tile Name</div>
    <div class="tileContent">
       //lots of stuff here.
    </div>
</div>

目前所有这些都是动态创建的,所以这是我当前的代码:

let $elTile = $('<div/>', {
    class: 'tile'
}).appendTo($elContainer);

let $elTileHeader = $('<div/>', {
    class: 'tileHeader',
    html: tile.header
}).appendTo($elTile);

let $elTileContent = $('<div>').load('tile-content.html #' + tile.name + '-tile');
$elTile.append($elTileContent);

上面最后两行的灵感来自this solution。不幸的是,它增加了一个额外的&lt;div&gt;,我想避免这样做:

<div class="tile">
    <div class="tileHeader">Tile Name</div>
    <div> <!-- I don't want this -->
        <div class="tileContent">
           <!-- lots of stuff here. -->
        </div>
    <div>
</div>

我怎样才能得到想要的解决方案?


有几个类似的问题,但我发现没有一个有解决方案,而且我的情况略有不同(动态创建的元素)。

【问题讨论】:

  • 额外的 div 到底出现在哪里?
  • ($elTileContent).appendTo($elTile);
  • 为您添加了示例。

标签: javascript jquery html jquery-load


【解决方案1】:

这是因为您在这里自己创建了那个额外的 div:

let $elTileContent = $('<div>').load(...)

您应该加载内容,然后添加标题:

//create the tile and add it to the container
let $elTile = $('<div/>', {
    class: 'tile'
}).appendTo($elContainer);

//create the header but do not add it yet
let $elTileHeader = $('<div/>', {
    class: 'tileHeader',
    html: tile.header
})

//load the content into the tile
$elTile.load('tile-content.html #' + tile.name + '-tile', function(){
    //on the "complete" callback, prepend the header
    $elTile.prepend($elTileHeader);
});

快乐编码:)

【讨论】:

  • 哇,不知道为什么我没有想到先加载内容然后添加标题。非常简单。谢谢。
  • 谢谢,然后接受回答:P哈哈..开玩笑:)
  • 由于某种原因它不起作用。我不确定这是否与我的循环有关,或者与加载瓷砖的砖石有关。我会尝试发布更多详细信息。
  • 究竟是什么不工作,请分享,以便我可以帮助
  • 覆盖.tileHeader
【解决方案2】:

你告诉它在这一行给出额外的 div:

let $elTileContent = $('<div>).load('tile-content.html #' + tile.name + '-tile')

您需要先使用 tile 类对元素进行加载,然后对标题 div 元素使用 .prepend 而不是 append,以便它堆叠在加载的内容 div 之上。

【讨论】:

  • 如果我“首先使用 tile 类加载元素”,它将覆盖 .tileHeader 元素,不是吗?
猜你喜欢
  • 2015-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多