【发布时间】:2017-04-11 07:27:28
【问题描述】:
我正在使用 knockoutJs 处理选择输入下拉菜单,但在 knockoutJs 中使用 data-bind=with 时,选项值为空。谁能帮我解决这个问题。
Dropdown.html
<span class="price"><select data-bind="options: preferedTimeToPickup,optionsCaption: 'Dont Know or Does not Matter',
optionsText: 'name',value: preferedTimeToPickupVal" id="u3413_input" ></select>
</span>
自定义.js
this.preferedTimeToPickup =
[{name:"Morning (8-11)",price:5},
{name:"Lunch (11-2)",price:6},
{name:"Afternoon (2-5)",price:7},
{name:"Specific: 8:00",price:8.5},
{name:"Specific: 9:00",price:9.5},
{name:"Specific: 10:00",price:10.25},
{name:"Specific: 11:00",price:11.25},
{name:"Specific: 12:00",price:12.25},
{name:"Specific: 1:00",price:13.25},
{name:"Specific: 2:00",price:14.25},
{name:"Specific: 3:00",price:15.25},
{name:"Specific: 4:00 (closed at 4 on sat)",price:16.25}];
this.preferedTimeToPickupVal = ko.observable();
使用下面的html显示数据
<p data-bind="with: preferedTimeToPickupVal">
<span data-bind="text: name"></span>
</p>
<p data-bind="with: preferedTimeToPickupVal">
<span data-bind="text: price"></span>
</p>
到目前为止一切正常,但在选择下拉列表中value="" 为空,如果我在input type select 中使用optionsValue: 'name',则值呈现正常但data-bind="with: preferedTimeToPickupVal 无法在我想要的地方工作显示数据。
任何帮助将不胜感激。
【问题讨论】:
-
在使用淘汰赛时不要依赖
document.getElementById('id').value。value绑定允许您存储的不仅仅是字符串,这在您的情况下非常有用(因为它支持具有with绑定的部分)。良好做法:如果您在其他地方需要value,请链接到您的视图模型。不好的做法:至少使用ko.dataFor(element).preferedTimeToPickupVal().price从 DOM 中检索所选价格。
标签: javascript jquery knockout.js