繁体   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