gpt4 book ai didi

javascript - 如何让 Knockout JS 在按键上进行数据绑定(bind)而不是失去焦点?

转载 作者:IT老高 更新时间:2023-10-28 13:15:04 26 4
gpt4 key购买 nike

knockout js 这个例子因此,当您编辑字段并按 TAB 时, View 模型数据以及字段下方的文本都会更新。

如何更改此代码,以便每次按键都更新 View 模型数据?

alt text

<!doctype html>
<html>
<title>knockout js</title>
<head>
<script type="text/javascript" src="js/knockout-1.1.1.debug.js"></script>
<script type="text/javascript">
window.onload= function() {

var viewModel = {
firstName : ko.observable("Jim"),
lastName : ko.observable("Smith")
};
viewModel.fullName = ko.dependentObservable(function () {
return viewModel.firstName() + " " + viewModel.lastName();
});

ko.applyBindings(viewModel);
}
</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>

最佳答案

<body>
<p>First name: <input data-bind="value: firstName, valueUpdate: 'afterkeydown'" /></p>
<p>Last name: <input data-bind="value: lastName, valueUpdate: 'afterkeydown'" /></p>
<h2>Hello, <span data-bind="text: fullName"> </span>!</h2>
</body>

来自 documentation

Additional parameters

  • valueUpdate

    If your binding also includes a parameter called valueUpdate, this defines which browser event KO should use to detect changes. The following string values are the most commonly useful choices:

    • "change" (default) - updates your view model when the user moves the focus to a different control, or in the case of elements, immediately after any change

    • "keyup" - updates your view model when the user releases a key

    • "keypress" - updates your view model when the user has typed a key. Unlike keyup, this updates repeatedly while the user holds a key down

    • "afterkeydown" - updates your view model as soon as the user begins typing a character. This works by catching the browser’s keydown event and handling the event asynchronously.

Of these options, "afterkeydown" is the best choice if you want to keep your view model updated in real-time.

关于javascript - 如何让 Knockout JS 在按键上进行数据绑定(bind)而不是失去焦点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4386311/

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