给定这个 HTML:
index.html:
<div class="tile" data-tilename="test"> <div class="tileHeader">Tile Name</div> </div>
tile-content.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 。不幸的是它增加了一个额外的 <div>
我想避免:
<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:
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);
});
快乐编码:)
关于javascript - 从另一个页面追加元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44976420/