首页 新闻 会员 周边 捐助

knockout.js 绑定问题

0
悬赏园豆:5 [待解决问题]
 1 <!DOCTYPE html>
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4     <title>Test</title>
 5     <script src="knockout-3.3.0.js"></script>
 6 </head>
 7 <body>
 8     
 9     <div class='liveExample'>
10         <p>First name: <input data-bind='value: firstName' /></p>
11         <p>Last name: <input data-bind='value: lastName' /></p>
12         <h2>Hello, <span data-bind='text: fullName'> </span>!</h2>
13     </div>
14     <script type='text/javascript'>
15         var ViewModel = function (first, last) {
16             this.firstName = ko.observable(first);
17             this.lastName = ko.observable(last);
18 
19             this.fullName = ko.computed(function () {
20                 return this.firstName() + " " + this.lastName();
21             }, this);
22         };
23 
24         ko.applyBindings(new ViewModel("Planet", "Earth"));
25     </script>
26 </body>
27 </html>

这样运行可以但是下面这段就不可以

 1 <!DOCTYPE html>
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4     <title>Test</title>
 5     <script src="knockout-3.3.0.js"></script>
 6 </head>
 7 <body>
 8     <script type='text/javascript'>
 9         var ViewModel = function (first, last) {
10             this.firstName = ko.observable(first);
11             this.lastName = ko.observable(last);
12 
13             this.fullName = ko.computed(function () {
14                 return this.firstName() + " " + this.lastName();
15             }, this);
16         };
17 
18         ko.applyBindings(new ViewModel("Planet", "Earth"));
19     </script>
20     <div class='liveExample'>
21         <p>First name: <input data-bind='value: firstName' /></p>
22         <p>Last name: <input data-bind='value: lastName' /></p>
23         <h2>Hello, <span data-bind='text: fullName'> </span>!</h2>
24     </div>
25     
26 </body>
27 </html>
jack89son的主页 jack89son | 初学一级 | 园豆:12
提问于:2015-06-24 00:02
< >
分享
所有回答(1)
0

后一个不好使应该是因为执行js代码的时候后面的DOM元素还没有生成,因为HTML是自上而下执行的,使用jquery将js代码写在DOM的ready事件中就不用担心这个问题了。

芝芝07 | 园豆:365 (菜鸟二级) | 2015-06-24 09:10
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册