gpt4 book ai didi

javascript - knockout : How to get default item from select option and pass as argument to another function when page loads?

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

我有一个通过绑定(bind)填充的选择选项。根据所选值或默认值,Continent 作为参数传递给另一个函数,该函数使用与所选大陆相关的国家/地区信息填充表格。简而言之,该表是根据大陆填充的,但这也是在页面首次加载时完成的:

这是一个complete Fiddle example :

其他信息:

enter image description here

当使用表中的第一条记录加载页面时,我尝试加载国家/地区详细信息的其他数据。我需要将国家/地区 ID 传递回 View 模型中的函数

插图:

enter image description here

目前,我正在使用点击事件来填充附加数据,如下所示:

<table id="country-list">
<thead>
<tr>
<th>CountryID</th>
<th>Country Name</th>
<th>City</th>
<th>Continent</th>
<th>CountryAbbr</th>
</tr>
</thead>
<tbody data-bind= "foreach: FilteredCountries">

<!-- Return row data to CountryDetails and use the info to
bind data based on row clicked-->

<tr data-bind="click: $root.CountryDetails, clickBubble: false">
<td data-bind="text: CountryId"></td>
<td data-bind="text: Country"></td>
<td data-bind="text: City"></td>
<td data-bind="text: Continent"></td>
<td data-bind="text: CountryAbbr"></td>
</tr>
</tbody>
</table>

代码:

self.CountryDetails = function(country)
{
var data = ko.computed(function() {

return ko.utils.arrayFilter(self.CountryDetailData(), function(item) {
return item.CountryId === country.CountryId;
});
});

self.CountryId(data()[0].CountryId);
self.Location(data()[0].Location);
self.Coordinates(data()[0].Coordinates);
self.Coastline(data()[0].Coastline);
self.Climate(data()[0].Climate);
self.Terrain(data()[0].Terrain);
}

Complete example code in fiddle:

最佳答案

只需在绑定(bind)模型后使用 FilteredCountries 中的第一个国家/地区调用 CountryDetails 即可:

var vm = new ViewModel;
ko.applyBindings(vm);

vm.CountryDetails(vm.FilteredCountries()[0]);

您还可以使用以下命令突出显示所选行:

// CSS
tbody tr.active { background-color: #ccc; }

// HTML
<tr data-bind="click: $root.CountryDetails, clickBubble: false, css: { active: $root.IsActiveRow(CountryId) }">

// JS
self.IsActiveRow = function (countryId) {
return countryId == self.CountryId();
}

查看更新Fiddle

关于javascript - knockout : How to get default item from select option and pass as argument to another function when page loads?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33852674/

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