簡體   English   中英

模板標簽不包含內容

[英]template tag does not include content

我在模板中包裝了一些html,但是當我嘗試激活模板並更改模板中的某些元素時,它返回為null。 我在模板上完成了console.log,然后返回的只是模板標記和結束標記的開始,例如<template id="panel-template"></template>這是渲染的版本,您可以看不到應該封裝的html都不存在。

這是我的模板

<template id="panel-template">
<div class="panel panel-default" draggable="true">
    <div class="panel-heading">
        <h3 class="panel-title">
            Panel title
            <span class="glyphicon glyphicon-pencil panel-icons"></span>
            <span class="glyphicon glyphicon-zoom-in panel-icons"></span>
            <span class="glyphicon glyphicon-trash panel-icons"></span>
        </h3>
    </div>
    <div class="panel-body">
    </div>
</div>

這是與模板相關的javascript的一部分,我當然將其包裝在document.ready中

if ('content' in document.createElement('template')) {

                    //var widgetCount = document.getElementById('columns').getAttribute('data-count');
                    var widgetModel = @Html.Raw(Json.Encode(Model.widgets));

                    for (var i = 0; i < widgetModel.length; i++) {
                        var clone = loadwidgets(widgetModel[i]); //This function is in an external js file
                        var inputDestination = document.querySelector('#col2')
                        console.log(inputDestination);
                        inputDestination.appendChild(clone);
                    }
                }

這是loadWidgets函數。

function loadwidgets (jsonObject) {
var template = document.querySelector('#panel-template');
var panelTitle = template.querySelector('div.panel-title');
var widgetType = template.querySelector('div.panel-body');

console.log(template);

//We give the widget a name on top of panel, this will be user defined.
panelTitle.textContent = jsonObject.WidgetName;
widgetType.setAttribute('id', jsonObject.WidgetCode);

return document.importNode(template, true);

}

我收到一個錯誤消息,指出panelTitle為null,但是我認為這是因為在激活模板時,它似乎並未遍歷封裝的html元素。 我不確定如何進行。

我在您的Javascript部分中看到您聲明要創建一個元素。 您需要啟動代碼。 但我看不到您將元素“模板”放到火盆里

您應該在模板的content屬性上使用querySelector()

var panelTitle = template.content.querySelector('div.panel-title');

如您提供的鏈接中所述。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM