简体   繁体   English

淘汰赛:名字-姓氏加入者不起作用

[英]Knockout: First Name - Last Name Joiner Not Working

I am trying to use knockout and join together a first name and a last name which the user inputs. 我正在尝试使用淘汰赛,并将用户输入的名字和姓氏结合在一起。 It is based off of this example: http://knockoutjs.com/examples/helloWorld.html 它基于以下示例: http : //knockoutjs.com/examples/helloWorld.html

I tried changing the functions a bit to get a feel for knockout. 我尝试过一些更改功能,以感觉到淘汰赛。 The code looked good, but the output didn't change. 代码看起来不错,但是输出没有改变。 I then tested to see if the exact code from the tutorial would work for me, but it doesn't. 然后,我测试了教程中的确切代码是否对我有用,但是没有用。 I'm pretty sure I'm missing something really obvious. 我敢肯定,我确实缺少一些明显的东西。 Can someone tell me what that is? 有人可以告诉我那是什么吗?

This is my HTML: 这是我的HTML:

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<!--view-->
<head>
    <meta charset="utf-8" />
    <title>Testing Knockout</title>
    <script src="knockoutTester.js"></script>
    <script src="knockout-3.4.0.js"></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>

This is my JS: 这是我的JS:

var ViewModel = function (first, last) {
    this.firstName = ko.observable(first);
    this.lastName = ko.observable(last);

    this.fullName = ko.pureComputed(function () {
        return this.firstName() + " " + this.lastName();
    }, this);
};    
ko.applyBindings(new ViewModel("Planet", "Earth"));

Thanks 谢谢

Your JS code is fine. 您的JS代码很好。 The problem is the order in which you added JS files in your HTML file: 问题是在HTML文件中添加JS文件的顺序:

<script src="knockoutTester.js"></script>
<script src="knockout-3.4.0.js"></script>

In order for your code to work you need to load Knockout first, and only then load your custom code. 为了使代码正常工作,您需要先加载Knockout,然后才加载自定义代码。 So change above lines to 因此将以上行更改为

<script src="knockout-3.4.0.js"></script>
<script src="knockoutTester.js"></script>

and it should start working. 它应该开始工作。

You also need to make sure that your custom JavaScript code runs only after DOM is loaded, because all DOM elements should be loaded when the scripts are run. 您还需要确保自定义JavaScript代码仅在加载DOM之后才运行,因为在运行脚本时应加载所有DOM元素。 You can use jQuery 's method $(document).ready or use any other alternative (eg as described in $(document).ready equivalent without jQuery ). 您可以使用jQuery的方法$(document).ready或使用任何其他替代方法(例如,在使用jQuery$(document).ready中进行描述)。

Alternatively you could include the line <script src="knockoutTester.js"></script> at the bottom of the body (so it only loads after DOM above is loaded) 或者,您可以在正文底部添加<script src="knockoutTester.js"></script> (因此,仅在加载了上面的DOM之后才加载)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM