0

可能重复:
KnockoutJS:ko.applyBindings 到部分视图?

我使用 jQuery 淘汰赛。作为下面的基本示例的结果,文本"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

1 回答 1

2

要使其工作,您必须修改 4 行:

申请id

<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"));
于 2013-01-18T11:47:33.040 回答