gpt4 book ai didi

javascript - 默认情况下,选择值绑定(bind)不会在没有显式值的情况下填充

转载 作者:行者123 更新时间:2023-11-30 05:39:03 25 4
gpt4 key购买 nike

我正在尝试使用手动选择值绑定(bind)来获取所选对象的 ID,但我发现它不会填充,除非给出明确的值。这是一个例子:

<div id="container">
<select data-bind="value: selectedOption">
<!-- notice the explicit value of 0 given below... why is that necessary to get selectedOption to be populated when bound? -->
<option value="0" data-bind="value: initialSelectedOptionId, text: 'initially selected option'"></option>
<!-- ko foreach: options -->
<option data-bind="value: id, text: name"></option>
<!-- /ko -->
</select>
<span data-bind="text: selectedOption"></span>

var viewModel = {
options: ko.observableArray([
{id: 1, name: 'first option'},
{id: 2, name: 'second option'},
{id: 3, name: 'third option'},
{id: 4, name: 'fourth option'}
]),
selectedOption: ko.observable(),
initialSelectedOptionId: ko.observable(3)
};
ko.applyBindings(viewModel, document.getElementById('container'));
//uncommenting the following line will initially select the correct option
//viewModel.selectedOption(viewModel.initialSelectedOptionId());

Here是显示实际问题的 jsfiddle。请注意,selectedOption 属性在显式时会被填充,但在完成绑定(bind)时不会。这种行为是错误吗?如果不是,该决定背后的原因是什么?

最佳答案

这是否符合您的预期?

<div id="container">
<select data-bind="value: selectedOption">
<!-- notice the explicit value of 0 given below... why is that necessary to get selectedOption to be populated when bound? -->
<option data-bind="value: initialSelectedOptionId, text: 'initially selected option'"></option>
<!-- ko foreach: options -->
<option data-bind="value: id, text: name"></option>
<!-- /ko -->
</select>
<span data-bind="text: selectedOption"></span>

var viewModel = {
options: ko.observableArray([
{id: 1, name: 'first option'},
{id: 2, name: 'second option'},
{id: 3, name: 'third option'},
{id: 4, name: 'fourth option'}
]),
selectedOption: ko.observable(3),
initialSelectedOptionId: ko.observable(0)};

ko.applyBindings(viewModel, document.getElementById('container'));
//uncommenting the following line will initially select the correct option
viewModel.selectedOption(3);

Fiddle here to see it working .

我认为在应用绑定(bind)后如果不设置 selectedOption 就无法工作的原因是绑定(bind)发生的顺序。 <select data-bind="value: selectedOption">首先绑定(bind),并且由于尚未绑定(bind)任何下拉选项,因此 KO 无法正确应用此绑定(bind)。

我跟踪了selectedOption的值,发现应用绑定(bind)后直接设置为空字符串。我猜想当它将绑定(bind)应用到 DOM 时,KO 已经更新了这个值(通过 2 向绑定(bind))以匹配下拉列表的“选定值”(因为在那个阶段没有绑定(bind)任何项目) .从那时起(当然,直到您修改它)到 selectedOption 的所有绑定(bind)都将显示为空白。

有道理吗?

关于javascript - 默认情况下,选择值绑定(bind)不会在没有显式值的情况下填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21867504/

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