对于 Metro 风格的应用程序,在 Windows 8 中,我有一个我传递给翻转视图控件的文章列表。每篇文章都有一个包含 javascript 的 HTML 描述文本。我知道我们必须使用这个函数将不安全的内容加载到 innerHTML :
var someElement = document.getElementById('someElementID');
MSApp.execUnsafeLocalFunction(
function() { someElement.innerHTML = '<div onclick="console.log(\"hi\");">hi</div>' }
);
但是当我的 innerHTML 属性在模板中时,我该如何实现呢?
这是我的模板:
<div id="ItemTemplate" data-win-control="WinJS.Binding.Template">
<div class="itemDetail fragment">
<header aria-label="Header content" role="banner">
<!-- <button class="win-backbutton" aria-label="Back" disabled></button>-->
<h1 class="titlearea win-type-ellipsis">
<span class="pagetitle"></span>
</h1>
</header>
<section aria-label="Main content" role="main">
<article>
<img class="article-image" src="#" style="width: 300px; height: 200px;" data-win-bind="src: urlImage; alt: title" />
<div class="item-content" data-win-bind="innerHTML: description"></div>
</article>
</section>
</div>
</div>
对于这个翻转视图:
<div id="basicFlipView"
data-win-control="WinJS.UI.FlipView"
data-win-options="{itemTemplate:select('#ItemTemplate')}">
</div>
这是我填写的方法:
var dataControl = document.getElementById("basicFlipView").winControl;
dataControl.itemDataSource = dataList.dataSource;
dataControl.currentPage = myState.index;
非常感谢您的帮助
编辑:正如 Dominic Hopton 建议的那样,我使用了 WinJS.Binding.initializer。这是一种非常复杂的绑定方式。我已经这样做了,但它不能正常工作。你有没有发现不对劲:
var toUnsafeHTML = WinJS.Binding.initializer(
function toUnsafeHTML(source, sourceProperty, dest, destProperty) {
function setUnsafeHTML() {
MSApp.execUnsafeLocalFunction(
function () { dest.innerHTML = source.innerHTML }
);
}
return WinJS.Binding.bind(source, {
innerHTML : setUnsafeHTML}
);
}
);
//
// Binding initializers have to be public, so publish this out
// via a namespace
//
WinJS.Namespace.define("TemplateControl", {
toUnsafeHTML: toUnsafeHTML
});
并在 html 中:
<div id="ItemTemplate" data-win-control="WinJS.Binding.Template">
<div class="itemDetail fragment">
<header aria-label="Header content" role="banner">
<!-- <button class="win-backbutton" aria-label="Back" disabled></button>-->
<h1 class="titlearea win-type-ellipsis">
<span class="pagetitle"></span>
</h1>
</header>
<section aria-label="Main content" role="main">
<article>
<img class="article-image" src="#" style="width: 300px; height: 200px;" data-win-bind="src: urlImage; alt: title" />
<div class="item-content" data-win-bind="innerHTML: TemplateControl.toUnsafeHTML"></div>
</article>
</section>
</div>
</div>
它永远不会进入 setUnsafeHTML 函数......