简体   繁体   English

html() 未填充 HTML 模板

[英]html() is not populating HTML template

This is driving me crazy.这真让我抓狂。 Can anyone see what I'm doing wrong?谁能看到我做错了什么?

Here's my HTML template.这是我的 HTML 模板。

<template id="note-template">
    <div class="trip-note">
    </div>
    <div class="trip-note-footer">
        <div class="d-flex justify-content-between">
            <div>
                <span class="note-author"></span>
                &bull;
                <span class="note-date"></span>
            </div>
            <div>
                <img class="edit-note" src="~/images/tteditnote.png" title="Edit Note">
                <img class="delete-note" src="~/images/ttdeletenote.png" title="Delete Note">
            </div>
        </div>
    </div>
</template>

And here's my JavaScript.这是我的 JavaScript。

var $container = $('#trip-notes');
var $template = $('#note-template');
$container.empty();
response.forEach(function (element) {
    var $note = $($template.html());
    $note.find('.trip-note').html(element.html);
    $note.find('.note-author').text(element.author);
    $note.find('.note-date').text(element.createDate);
    $container.append($note);
});

Everything works exactly as expected except that my div.trip-note does not get set to the value in element.html .除了我的div.trip-note没有设置为element.html中的值之外,一切都按预期工作。

author and createDate are set just fine. authorcreateDate设置得很好。 I've confirmed element.html contains the expected markup.我已经确认element.html包含预期的标记。 I've retyped the class name several times (both in markup and in JavaScript).我已经多次重新输入了 class 名称(在标记和 JavaScript 中)。 I tried mixing and matching html() and text() and the result is always the same: All elements are populated except for div.trip-note .我尝试混合和匹配html()text()并且结果总是相同的:除了div.trip-note之外的所有元素都被填充。

I'm either missing something very stupid or there is a peculiar issue going on.我要么错过了一些非常愚蠢的东西,要么正在发生一个特殊的问题。

Update更新

I've created a jsfiddle .我创建了一个jsfiddle

.find() searches for descendants, it won't find the top-level element that you're searching from. .find()搜索后代,它不会找到您正在搜索的顶级元素。 Since .trip-note is one of the top-level elements of $note , it's note selected.因为.trip-note$note的顶级元素之一,所以它被选中了。

Instead of using $template.html() , make a clone of $template .不要使用$template.html() ,而是克隆$template Then everything will be a descendant.那么一切都将是一个后代。 You can use .html() when you're appending to $container to exclude the <template> top-level element.当您附加到$container以排除<template>顶级元素时,您可以使用.html()

 var $container = $('#trip-notes'); var $template = $('#note-template'); $container.empty(); response.forEach(function (element) { var $note = $template.clone(); $note.find('.trip-note').html(element.html); $note.find('.note-author').text(element.author); $note.find('.note-date').text(element.createDate); $container.append($note.html()); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM