在选择框中从任意 JavaScript 对象绑定选项值和选项文本
binding both optionValue and optionText in a select box from arbitrary JavaScript objects
我可以绑定选项文本,但不能绑定选项值。这两个函数应该相同吗?
呈现的 HTML:(值在哪里?
<option value="">ROSSFORD D</option>
视图:
<select multiple="multiple" width="75" id="foo" name="campaign[precincts][]" data-bind="options: campaign_precincts, optionsText: function(item) {
return item.precinct_location.id
}, optionsValue: function(foo) {return foo.precinct_location.id }> </select>
查看模型:
var newCampaign = function() {
this.items = ko.observableArray();
this.freeText = ko.observable("");
this.campaign_precincts = ko.observableArray();
this.selectedPct = ko.observable();
this.campaignName = ko.observable();
this.userParty = ko.observable("");
self = this;
var question = this.freeText();
this.searchMe = function() {
console.log (self.userParty());
self.items([]);
self.userParty()
if (this.freeText() != "") {
// search by city
$.getJSON('/search.json?q=' + this.freeText(), function (data) {
if (data) {
console.log(data)
data.forEach(function(item) { self.items.push(item) })
}
});
// search by zipcode
$.getJSON('/search.json?z=' + this.freeText(), function (data) {
if (data) {
data.forEach(function(item) { self.items.push(item) })
}
});
}
}.bind(this);
this.addPrecinct = function(pct) {
// returs false if pct is not a member of the array
x = function(a,b){return!!~a.indexOf(b)}
if ( x(self.campaign_precincts(),pct) == false) {
self.campaign_precincts.push(pct);
};
}.bind(this);
this.removePct = function() {
self.campaign_precincts.pop(self.selectedPct());
}
};
ko.applyBindings(new newCampaign());
js 对象:
data.precinct_location.city => "string"
data.precinct_location.id => 1234
KO 代码当前不考虑 a 函数是否传递给optionsValue
。 它有一个问题,并在这里讨论为绑定选项添加更全面和灵活的选项:https://github.com/SteveSanderson/knockout/pull/154
现在,您确实需要映射数据(即使只是在客户端),以便可以直接从数组项上的属性中读取值。 如果您在这部分需要任何帮助,我很乐意提供帮助。
相关文章:
- 重置为下拉菜单中的未绑定选项
- 在dojo中将数据从一个选项卡绑定到另一个选项卡(打开选项卡?)
- Knockout js 条件选项绑定
- 为什么我的淘汰选项绑定不起作用
- 如何使用淘汰选项绑定从select中删除值
- KnockoutJS 选项绑定,无法在父上下文中设置值
- 将可选选项绑定到下拉列表
- 模板内选项绑定的奇怪行为
- KO选项绑定在页面重新加载时将值保存为默认值
- 如何使用Knockout JS数组映射根据输入条件使选择选项绑定默认值
- KnockoutJS选项绑定有重复值
- Knockout.js选项绑定在ViewModel中不起作用
- 选择选项绑定&jQuery验证
- 取消选定的选项绑定
- 击倒选项绑定,嵌套optionsValue
- 将一个选择选项绑定到一个对象
- 奇怪的knockout js选择选项绑定问题
- 删除选项绑定:如果选项被选中,如何从弹出框中动态删除选项
- 如何将两个可编辑选择选项绑定在一起
- 两个下拉选项绑定基于ID knockoutjs