gpt4 book ai didi

javascript - Knockout.js - 简单的 "Hello World"失败

转载 作者:数据小太阳 更新时间:2023-10-29 04:05:22 26 4
gpt4 key购买 nike

我正在为 knockout js 做一个非常简单的 hello world(来自 http://goo.gl/lddLl):但是我的代码生成了一个我不明白的错误。

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>AJAX Example</title>
<script src="../Scripts/jquery-2.0.3.js"></script>
<script src="../Scripts/knockout-3.0.0.debug.js"></script>

<script>

// Here's my data model
var ViewModel = function (first, last) {
this.firstName = ko.observable(first);
this.lastName = ko.observable(last);

this.fullName = ko.computed(function () {
// Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
return this.firstName() + " " + this.lastName();
}, this);
};

ko.applyBindings(new ViewModel("Planet", "Earth")); // This makes Knockout get to work

</script>
</head>
<body>

<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>

</body>
</html>

ko.applyBindings 调用引发错误:

未捕获的类型错误:无法读取 null knockout-3.0.0.debug.js:2439 的属性“nodeType”

来自 knockout-3.0.0.debug.js 代码:

// Perf optimisation: Apply bindings only if...
// (1) We need to store the binding context on this node (because it may differ from the DOM parent node's binding context)
// Note that we can't store binding contexts on non-elements (e.g., text nodes), as IE doesn't allow expando properties for those
// (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)
var isElement = (nodeVerified.nodeType === 1);

我太无知了,不知道自己做错了什么......

最佳答案

我猜有 2 种解决方法。

1 最简单的方法:将脚本包装在里面

$(document).ready(function() {
your script goes here
});

使用 jQuery 的 ready() 函数延迟初始化,直到页面加载完毕。

2 将您的脚本移至:

<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>

HTML 是从上到下解析的。如果将脚本放在 html 元素之前,它们可能会在部分或所有页面元素准备好进行交互之前运行。

关于javascript - Knockout.js - 简单的 "Hello World"失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20225657/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com