【问题标题】:template tag does not include content模板标签不包含内容
【发布时间】:2015-08-07 20:06:12
【问题描述】:

我在模板中封装了一些 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 c# html asp.net-mvc-5 html5-template


    【解决方案1】:

    我在您的 Javascript 部分中看到您声明如果您创建一个元素。您需要启动代码。但我没有看到你在创建元素“模板”

    【讨论】:

    • html5rocks.com/en/tutorials/webcomponents/template 据我了解,如果我错了,请纠正我。它创建模板元素并检查元素中是否有 .content 属性。如果有,则表示它支持新的模板标签。这就是我从上面的链接中解释它的方式
    【解决方案2】:

    您应该在模板的content 属性上使用querySelector()

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

    如您提供的链接中所述。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 2019-12-31
      • 1970-01-01
      • 2015-07-25
      • 2017-01-05
      • 2016-08-12
      相关资源
      最近更新 更多