使用HTML模板和Jquery克隆将新面板添加到div
我有这个简单的html模板使用HTML模板和Jquery克隆将新面板添加到div,jquery,html,Jquery,Html,我有这个简单的html模板 <template id="templateDefaultPanel"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Panel title</h3> </div> <div c
<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>
小组标题
面板内容
我使用jqueryvar$panelTemplate=$(“#templateDefaultPanel”).clone()克隆它
然后修改内部html$panelTemplate.find('.panel body').html('hey there')然后将其设置为在另一个div$('#allNotes')上预结束($panelTemplate.html())代码>问题是$panelTemplate内容没有一个得到修改。然后,当我尝试prependTo
时,会插入模板,当然不会显示给用户
当我将模板切换到div时,我上面的所有代码都可以工作,但是如果我不能重用html,模板又有什么意义呢?你知道模板。毕竟,你必须创建一个div容器,并将模板内容添加到其中,然后在div元素之前添加模板。模板元素根本不会被渲染。
见:
还有一个例子。您不想克隆模板,因为您想要的是模板的内容,而不是模板本身,因此可以使用innerHTML
如果您看一下vanilla js示例,它会更有意义,因为您使用的是.content
而不是模板
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);
虽然我看到这个问题已经有了一个公认的答案,但如果您真的想/需要使用jQueryclone()
方法——可能是因为您还想通过clone(true)
包含数据和事件——那么您就不能将
元素用于正在克隆的内容
我不知道为什么,也没有看到任何说明原因的文档,但是如果您clone()
a
,那么没有其他jQuery方法可以对克隆的jQuery对象起作用
因此,就jQuery的使用而言,
元素似乎不如隐藏的
有用,除非我能够克隆
的内容,否则我很可能会使用它
另一方面,在
元素上使用clone()
实际上可以在IE中使用,但在任何所谓的“现代浏览器”中都不能使用。这很可能是因为IE对待
的方式与其他元素没有任何区别,但其他元素确实如此