可能重复:
KnockoutJS:ko.applyBindings到局部视图?
我在jQuery中使用了knockout。作为下面的基本示例的结果,文本"Planet Earth"
显示得很好(因此删除添加正确并且有效!(,但不显示"Planet2 Earth2"
。此外,alert('alert2');
被激发,但alert('alert3');
没有被激发。有人能解释一下为什么吗?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.9.0.min.js" type="text/javascript"></script>
<script src="Scripts/knockout-2.2.1.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
alert("alert1");
var viewModel = {
firstName: ko.observable("Planet"),
lastName: ko.observable("Earth")
};
viewModel.fullName = ko.dependentObservable(function () {
return viewModel.firstName() + " " + viewModel.lastName();
});
alert("alert2");
ko.applyBindings(viewModel);
alert('alert3');
var viewModel2 = {
firstName2: ko.observable("Planet2"),
lastName2: ko.observable("Earth2")
};
viewModel2.fullName2 = ko.dependentObservable(function () {
return viewModel2.firstName2() + " " + viewModel2.lastName2();
});
ko.applyBindings(viewModel2);
});
</script>
</head>
<body>
<div style="border:1px solid red;">
<p>First name: <input data-bind='value: firstName' /></p>
<p>Last name: <input data-bind='value: lastName' /></p>
<h2>Hello, <span data-bind='text: fullName'> </span>!</h2>
</div>
<div style="border:1px solid green;">
<p>First name: <input data-bind='value: firstName2' /></p>
<p>Last name: <input data-bind='value: lastName2' /></p>
<h2>Hello, <span data-bind='text: fullName2'> </span>!</h2>
</div>
</body>
</html>
要使其工作,您必须修改4行:
应用id
s:
<div id="one" style="border:1px solid red;">
和
<div id="two" style="border:1px solid green;">
以及对applyBindings使用第二个参数:
ko.applyBindings(viewModel,document.getElementById("one"));
和
ko.applyBindings(viewModel2,document.getElementById("two"));