使用 HTML 模板和 Jquery 克隆将新面板添加到 div 上



我有这个简单的html模板

<template id="templateDefaultPanel">
    <div class="panel panel-default"> 
        <div class="panel-heading"> 
            <h3 class="panel-title">Panel title</h3> 
        </div> 
        <div class="panel-body"> 
            Panel content 
        </div>
    </div>
</template>

我正在使用 jquery var $panelTemplate = $("#templateDefaultPanel").clone(); 克隆它,然后修改内部 html $panelTemplate.find('.panel-body').html('hey there');,然后将其设置为附加到另一个div $('#allNotes').prepend($panelTemplate.html());问题是$panelTemplate内容都没有被修改。然后当我尝试prependTo插入模板时,该模板当然不会向用户显示。

当我切换模板以div 时,我上面的所有代码都可以工作,但是如果我不能重用 html 并且您知道模板,模板有什么意义。

您不想克隆模板,因为您想要模板的内容,而不是模板本身,因此您可以使用innerHTML

如果你看一下香草JS的例子,它更有意义,因为你使用.content而不是template

const template = document.querySelector('#templateDefaultPanel');
template.content.querySelector('.panel-title').innerHTML = 'hello world';
template.content.querySelector('.panel-body').innerHTML = 'the body here';
const clone = document.importNode(template.content, true);
document.querySelector('#allNotes').appendChild(clone);
所以

你不是使用模板本身,而是使用它的内容,所以使用 jQuery 执行此操作的一种方式可能是

const $template = $( $('#templateDefaultPanel')[0].innerHTML );
// or alternatively get the content with .prop('content')
$template.find('.panel-title').html('hello world');
$template.find('.panel-body').html('the body here');
$('#allNotes').append($template);

毕竟,您必须创建一个div 容器并将模板内容添加到其中,然后在div 元素前面加上前缀。模板元素根本不会呈现。看:https://developer.mozilla.org/de/docs/Web/HTML/Element/template

还有一个例子。

虽然我看到这个问题已经有一个公认的答案,但如果你真的想要/需要使用 jQuery clone() 方法——也许是因为你还想通过 clone(true) 包含数据和事件——那么你不能将 <template> 元素用于你要克隆的内容。

我不知道为什么,我也没有看到任何文档来说明原因,但是如果您clone() <template>那么没有其他jQuery方法可以针对克隆的jQuery对象。

因此,就jQuery的使用而言,<template>元素似乎不如隐藏<div>有用,除非我可以clone() <template>的内容,否则这可能是我将使用的。

附带说明一下,在<template>元素上使用clone()实际上适用于IE,但不适用于任何所谓的"现代浏览器"。 这可能是因为IE对<template>的处理方式与任何其他元素没有任何不同,但其他元素却如此......

最新更新