Html 为什么我在使用 Knockout JS 时出现“无法读取 null 的属性‘nodeType’”错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15090015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 05:54:43  来源:igfitidea点击:

Why am I getting a "Cannot read property 'nodeType' of null" error with Knockout JS?

javascripthtmldata-bindingmvvmknockout.js

提问by Prasath K

Today is the first day for me in Knockout . Got struck with it . Below is my first sample code using knockout.js and it shows an error .

今天是我参加淘汰赛的第一天。被它打动了。下面是我使用 Knockout.js 的第一个示例代码,它显示了一个错误。

Cannot read property 'nodeType' of null

无法读取 null 的属性“nodeType”

Here is my script:`

这是我的脚本:`

   function ViewModel()  
   {  
     var self = this;  
     self.n1 = ko.observable(10);  
     self.n2 = ko.observable(10);  
     self.n3 = ko.observable(10);  
   }  
   ko.applyBindings(new ViewModel());  `

Here is my html:

这是我的 html:

<body>
<p>Number1:<input data-bind="value:n1"></input></p>
<p>Number2:<input data-bind="value:n2"></input></p>
<p>Number3:<input data-bind="value:n3"></input></p>
</body>

I want to know the reason for the above error and how to overcome it...

我想知道上述错误的原因以及如何克服它...

回答by Brigand

If you set up your code like this, it'll work.

如果您像这样设置代码,它将起作用。

<body>
<p>Number1:<input data-bind="value:n1"></p>
<p>Number2:<input data-bind="value:n2"></p>
<p>Number3:<input data-bind="value:n3"></p>
<script src="knockout.js"></script>
<script>

function ViewModel() {  
   var self = this;  
   self.n1 = ko.observable(10);  
   self.n2 = ko.observable(10);  
   self.n3 = ko.observable(10);
}  

ko.applyBindings(new ViewModel());  `

</script>
</body>

回答by lance-java

If you want to keep your <script>at the top of the page, you can use jQuery's ready() function to delay the initialization until the page has loaded.

如果你想保持你<script>在页面的顶部,你可以使用 jQuery 的 ready() 函数来延迟初始化,直到页面加载完毕。

$(document).ready(function() {
    ko.applyBindings(new ViewModel());
});

回答by Shemeer M Ali

I think ko.applyBindings(obj); should be write under view model.

我认为 ko.applyBindings(obj); 应该写在视图模型下。

<!DOCTYPE html>
<html>
<head>
    <title>KO Examples</title>
    <script type='text/javascript' src='knockout-3.1.0.js'></script>
    <script type='text/javascript' src='jquery.js'></script>
    <script type='text/javascript'>
        var  obj = {
            first_name : 'Gazal Irish'
        };


    </script>

</head>
<body>
<div>
    <p>My name : <span data-bind="text: first_name"></span>
<p> 
</div>
<script type="text/javascript">

    ko.applyBindings(obj);
</script>

</body>
</html>