我正在尝试最简单的knockout.js示例,但它不起作用(名字和姓氏保持空白)。我将脚本标签放在使用绑定的html标签之后,并在页面加载后调用ko.applyBindings。警报有效,因此功能触发。有什么帮助吗?
<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>
<script type="text/javascript' src='js/knockout-3.4.0.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function AppViewModel() {
alert("b");
this.firstName = "Bert";
this.lastName = "Bertington";
}
$(window).load(function() {
ko.applyBindings(new AppViewModel());
});
</script>
EDIT 这个问题解决了,但我有另一个问题。如果我想在点击按钮后同时添加名字和姓氏(而不是在输入失去焦点时)该怎么办?
<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<a class="btn btn-primary btn-lg" role="button" >Add</a>
<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>
<script type="text/javascript" src="js/knockout-3.4.0.js"></script>
<script type="text/javascript">
function AppViewModel() {
this.firstName = ko.observable();
this.lastName = ko.observable();
}
ko.applyBindings(new AppViewModel());
</script>
答案 0 :(得分:2)
脚本标记中的引号不匹配。它应该是:
<script type="text/javascript" src="js/knockout-3.4.0.js"></script>
您实际上可以完全删除type
属性,只需执行:
<script src="js/knockout-3.4.0.js"></script>
它仍然可以正常工作。
答案 1 :(得分:0)
一些事情:
$(document).ready
(或等效的$(function() ...
)代替$(window).load
; script
标记中的引号; 以下证明在这些更改之后它可以起作用:
function AppViewModel() {
alert("b");
this.firstName = "Bert";
this.lastName = "Bertington";
}
$(function() {
ko.applyBindings(new AppViewModel());
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>
&#13;