我有这个简单的 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('嘿那里');
然后将其设置为添加到另一个 div $('#allNotes').prepend($panelTemplate.html());
问题是 $panelTemplate 内容都没有被修改。然后当我尝试 prependTo
时,模板就会被插入,这当然不会向用户显示。
当我将 template 切换为 div 时,我上面的所有代码都可以工作,但是如果我无法重用 html 并且您知道模板,那么模板的意义何在。
最佳答案
您不想克隆模板,因为您想要模板的内容,而不是模板本身,因此您可以使用 innerHTML
如果你看一下 vanilla 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);
关于jquery - 使用 HTML 模板和 Jquery 克隆将新面板添加到 div 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49241513/