gpt4 book ai didi

javascript - 使用 knockout js 网站教程 - 如何将全名大写(而不仅仅是姓氏)?

转载 作者:行者123 更新时间:2023-11-29 10:55:39 25 4
gpt4 key购买 nike

我只是在消磨时间,用一些 knockout.js 弄脏我的手。我以前从未靠近过它,所以我想我应该看看它到底是怎么回事。

官网-http://learn.knockoutjs.com ,我已经修改了步骤 4/5 中的代码,这样当单击按钮时,按钮不会将 lastName 值变成大写,而是将 firstName 和 lastName 合并到名为 fullName 的变量中,并且更新 View 以显示 fullName all in大写。

关于我在这里做错了什么,伙计们,你知道吗?我只是想聚合/连接 firstName 和 lastName 的值,并将它们存储在一个名为 currentVal 的变量中,该变量在 View 中被分配给值 fullName。当我点击按钮时什么都没有发生 heh

这是我的代码(从教程的第 4/5 步修改而来,看看你能不能告诉我我可能在哪里做错了。

// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
function AppViewModel() {
this.firstName = ko.observable("Bert");
this.lastName = ko.observable("Bertington");

this.fullName = ko.computed(function() {
return this.firstName() + " " + this.lastName();
}, this);

this.capitalizeLastName = function() {
this.fullName = this.firstName() + " " + this.lastName(); //with or without this line, it doesn't update fullName to uppercase :-|
var currentVal = this.fullName();
this.fullName(currentVal.toUpperCase());
};
}

// Activates knockout.js
ko.applyBindings(new AppViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>
<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<p>Full Name: <input data-bind="value: fullName" /></p>
<p>Full Name: <strong data-bind="text: fullName"></strong></p>
<button data-bind="click: capitalizeLastName"> Go caps</button>

最佳答案

您好,您只需要更新您的 firstNamelastName 变量,因为 fullName 它是一个返回这些值的计算函数,如下所示:

function AppViewModel() {
this.firstName = ko.observable("Bert");
this.lastName = ko.observable("Bertington");

this.fullName = ko.computed(function() {
return this.firstName() + " " + this.lastName();
}, this);

this.capitalizeFullName = function() {
this.lastName(this.lastName().toUpperCase());
this.firstName(this.firstName().toUpperCase());
};
}

ko.applyBindings(new AppViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>
<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<p>Full Name: <input data-bind="value: fullName" /></p>
<p>Full Name: <strong data-bind="text: fullName"></strong></p>
<button data-bind="click: capitalizeFullName"> Go caps</button>

关于javascript - 使用 knockout js 网站教程 - 如何将全名大写(而不仅仅是姓氏)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58105046/

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