且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Windows 8 metro javascript app绑定到表

更新时间:2022-02-14 06:50:40

你不能像这样使用 ListView ListView 控件添加了一大堆额外的元素来完成它的工作,这导致你的表问题。

You can't use a ListView like this. The ListView control adds a whole stack of extra elements to do its work, which is causing your table problems.

答案是直接使用 WinJS.Binding.Template 控件用它来在表元素中插入行ere是模板所需的HTML:

The answer is to work with the WinJS.Binding.Template control directly and use it to insert rows into your table element. Here is the HTML you'll need for the template:

<table >
    <tbody id="myTemplate" data-win-control="WinJS.Binding.Template">
        <tr >
            <td data-win-bind="innerText: label"></td>
            <td data-win-bind="innerText: value"></td>
            <td></td>
        </tr>
    </tbody>
</table>

您需要输入一个完整的表格并且 tbody 在标记中,以便浏览器不会对查找未附加的tr元素或插入tbody元素本身感到不安。模板的外部元素将被丢弃,因此在您使用模板时,只会生成 tr 元素。

You need to put a complete table and tbody in the markup so that the browser doesn't get upset about finding an unattached tr element or insert the tbody element itself. The outer element of a template is discarded, so only the tr element will be generated from the template when you use it.

这是表的标记,其中将插入生成的元素 - 这是你所拥有的,除了我添加了一个id属性,所以我可以找到从Javascript插入内容的元素:

Here is the markup for the table, where the generated elements will be inserted - this is what you had, except I have added an id attribute so I can find the element to insert content into from Javascript:

<table>
    <thead>
        <tr>
           <th>col1</th>
           <th>col2</th>
           <th>col2</th>
        </tr>
    </thead>     
    <tbody id="myTableBody">
    </tbody>
</table>

最后,这是代码:

WinJS.UI.processAll().then(function () {
    var tableBody = document.getElementById("myTableBody");
    var template = document.getElementById("myTemplate").winControl;

    topContent.forEach(function (item) {
        template.render(item, tableBody);
    });
});

您需要确保承诺在使用模板之前, WinJS.UI.processAll 返回。为要处理的每个项调用 render 方法 - 参数是要传递给模板以进行数据绑定的数据项,以及用于将生成的元素插入的DOM元素。

You need to make sure that the Promise returned by WinJS.UI.processAll is fulfilled before you use the template. Call the render method for each item you want to process - the arguments are the data item to pass to the template for data binding and the DOM element to insert the generated elements into.