javascript - 从另一个页面追加元素?

标签 javascript jquery html jquery-load

给定这个 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/

相关文章:

javascript - ajax 加载的单个复选框在 javascript 验证中显示未定义

javascript - 如何添加一个在 HTML 渲染时执行的处理程序?

html - 这支笔的侧边栏在哪里?

javascript - 由于 `quote` 符号,在连接期间防止错误的常用方法

javascript - 访问 strg 名称为数字的对象

javascript - 使用 jquery 和 javascript 获取标签名称

javascript - 在有多个条目的情况下使用 jQuery 计算字符数

javascript - 似乎一个元素的 onBlur 是 "overriding"另一个元素的 onclick

jquery - 带有 farbtastic 颜色选择器内容的 Twitter Bootstrap Popover.js 丢失附加事件

javascript - JQuery 验证不适用于 ajax post