gpt4 book ai didi

javascript - knockout : How to select an item by property name from an observableArray of objects

转载 作者:行者123 更新时间:2023-11-28 15:08:21 24 4
gpt4 key购买 nike

我正在通过开发一个小应用程序来打印有关选定人员的信息来迈出 knockout 的第一步,问题是我不知道如何根据特定属性从数组中选择对象。

在我的 fiddle 中,我需要打印有关我选择的人的所有信息,但人名没有出现在选择框中,它显示[Object Object]

为了获得我想要的结果,我缺少什么?

var people = [{
name: "Contact 1",
address: "1, a street, a town, a city, AB12 3CD",
tel: "0123456789",
email: "anemail@me.com",
type: "family"
}, {
name: "Contact 2",
address: "1, a street, a town, a city, AB12 3CD",
tel: "0123456789",
email: "anemail@me.com",
type: "friend"
}, {
name: "Contact 3",
address: "1, a street, a town, a city, AB12 3CD",
tel: "0123456789",
email: "anemail@me.com",
type: "friend"
}];

function ContactsViewModel(people) {
var self = this;
self.contacts = ko.observableArray(people);
}

ko.applyBindings(new ContactsViewModel(people));
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div>
Show me:
<select data-bind="options: contacts"></select>
</div>
<div>
Name: <span databind="text: name"></span><br>
Adress: <span data-bind="text: address"></span><br>
Tel: <span data-bind="text: tel"></span><br>
Email: <span data-bind="text: email"></span><br>
Type: <span data-bind="text: type"></span><br>
</div>

我的 fiddle :http://jsfiddle.net/VxT5Y/146/

最佳答案

使用 select optionsText 数据绑定(bind)属性:

 <select data-bind="options: contacts,
optionsText: 'name',
value: selectedName,
optionsCaption: 'Choose...'"></select>

关于javascript - knockout : How to select an item by property name from an observableArray of objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37889206/

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