如何在每个表行上放置click事件,并将结果作为参数传递,以将新数据绑定到另一个源

How to place click event on each table row and pass result as argument to bind new data to another source?

本文关键字:参数传递 结果 另一个 数据绑定 事件 click      更新时间:2023-09-26

我有以下代码,它填充一个select options,并将所选值传递给视图模型中的另一个函数,该函数用与所选值匹配的数据填充一个表:

简而言之,如果用户从选择选项中选择ASIA,则ASIA中的所有国家都绑定到该表:

Fiddle示例:

如何向表中的每一行添加单击事件,以便将作为参数单击的行的CountryId传递给View Model中的另一个函数?我需要使用参数和函数来执行额外的绑定。例如:Country Detail

这就是我目前所拥有的:

<div id="country-select">
    <select data-bind="options: UniqueContinent,
                       value: SelectedContinent"></select>
</div>
<table id="country-list">
    <tr>
        <th>CountryID</th>
        <th>Country Name</th>
        <th>City</th>
        <th>Continent</th>
        <th>CountryAbbr</th>
    </tr>
    <tbody data-bind= "foreach: FilteredEntries">
    <tr>
        <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>

JS代码:

function ViewModel() {
    var self = this;
    self.CountryData = ko.observableArray([
  {
    "City": "KABUL",
    "Continent": "ASIA",
    "Country": "AFGHANISTAN",
    "CountryAbbr": "AF",
    "CountryId": "102120"
  },
   {
    "City": "DHAKA",
    "Continent": "ASIA",
    "Country": "BANGLADESH",
    "CountryAbbr": "BD",
    "CountryId": "102136"
  },       
  {
    "City": "BRUSSELS",
    "Continent": "EUROPE",
    "Country": "BELGIUM",
    "CountryAbbr": "BE",
    "CountryId": "102139"
  },
  {
    "City": "MINSK",
    "Continent": "EUROPE",
    "Country": "BELARUS",
    "CountryAbbr": "BY",
    "CountryId": "102138"
  }]);
    self.SelectedContinent = ko.observable('');
    self.UniqueContinent = ko.dependentObservable(function() {
        var continent = ko.utils.arrayMap(self.CountryData(),
            function(item){
                return item.Continent
            })
        return ko.utils.arrayGetDistinctValues(continent).sort();
    });
    // Call this function when changes are made
    self.FilteredEntries = ko.computed(function() {
        return ko.utils.arrayFilter(self.CountryData(), function(item) {
            // I need to use the selected value
            return item.Continent === self.SelectedContinent();
        });
    });
}
ko.applyBindings(new ViewModel)

只需在<tr>:中添加一个click处理程序

<tr data-bind="click: $root.CountryDetails">

在你的脚本中:

self.CountryDetails = function(country)
{
    doSomethingWithCountryId(country.CountryId);
}
function doSomethingWithCountryId(countryId)
{
    // ...
}

请参阅更新的Fiddle和文档