可以綁定使用ko.applyBindings(視圖模型,ElementSelector)頁面加載後的元素,就像這樣:
ko.applyBindings(myModel, $("#myDiv"));
然而,這是不是你通常想要做的事。在Knockout中使用If綁定會更容易,它會動態添加或刪除頁面中的子元素。
<input type="checkbox" data-bind='checked: showChild' />
<div id="container" data-bind="if: showChild">
<!-- stuff here will only be generated if the checkbox is selected -->
</div>
如果你有多個不同的元素基礎上的東西值顯示,說一個選擇列表,你可以使用模板功能來代替:
//viewmodel properties
self.Options = ko.observableArray(["Name", "Age", "Height"])
self.TemplateToUse = ko.observable()
//html
<select data-bind="options: Options, value: TemplateToUse">
</select>
<div data-bind='template: { name: TemplateToUse }'>
<!-- template whose name is selected value -->
</div>
//templates
<script type="text/html" id="Age">
<span>Age</span>
</script>
<script type="text/html" id="Name">
<span>Name</span>
</script>
<script type="text/html" id="Height">
<span>Height</span>
</script>
感謝@SarahBourt,我很期待實施它,從來不知道模板在淘汰賽。我將其標記爲答案。 – Parshii
乾杯。如果您還沒有,請前往http://knockoutjs.com/documentation/introduction.html上的Knockout.js的文檔部分。Knockout有很棒的文檔:) –
我知道。謝謝@SarahBourt我會繼續這樣做。 – Parshii