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