我非常高兴我第一次使用Knockout.js,非常棒的库,但我仍然试图围绕它的模板功能,例如这个非常简单的联系人应用程序,我想生成一个表每个新联系人的行: h3Contact/h3pFirst Name: input data-bi
<h3>Contact</h3> <p>First Name: <input data-bind="value: contactFirstName" /></p> <p>Last Name: <input data-bind="value: contactLastName" /></p> <p>Email Address: <input data-bind="value: contactEmailAddress" /></p> <button data-bind="click: addContact">Add</button> <table> <thead> <tr> <td>First Name</td> <td>Last Name</td> <td>Email Address</td> </tr> </thead> <tbody data-bind="template: {name: 'contactsTemplate', foreach: contacts}" /> </table> <script id="contactsTemplate" type="text/html"> <tr> <td>${ $data.firstName }</td> <td>${ $data.lastName }</td> <td>${ $data.emailAddress }</td> </tr> </script> <script type="text/javascript"> function contact(firstName, lastName, emailAddress) { return { firstName: ko.observable(firstName), lastName : ko.observable(lastName), emailAddress: ko.observable(emailAddress) }; } var viewModel = { contactFirstName: ko.observable("Peter"), contactLastName: ko.observable("Gibbons"), contactEmailAddress: ko.observable("peter.gibbons@initech.com"), equipments: ko.observableArray([new equipment("Peter", "Gibbons", "peter.gibbons@initech.com")]), addEquipment: function () { this.equipments.push(new equipment("Peter", "Gibbons", "peter.gibbons@initech.com")); } }; ko.applyBindings(viewModel); </script>
绑定工作正常,但我感到沮丧,因为它似乎嵌套了全新的< tr>在第一个< td>内.它发生在Iexplore和Firefox上.
任何建议都将得到真诚的感谢,非常感谢您的指导.
编辑
更新了标记以反映RP Niemeyer的贡献.
你可以替换这一行:<tr data-bind="template: {name: 'contactsTemplate', foreach: contacts}" />
有:
<tbody data-bind="template: {name: 'contactsTemplate', foreach: contacts}"></tbody>