【发布时间】: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