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

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

我有以下代码填充 select options 并将 selected 值传递给视图模型中的另一个函数,该函数用匹配 select 的数据填充 table =]ed值:

简而言之,如果用户 selects ASIA 来自 select 选项,则 ASIA 中的所有国家/地区都绑定到 table:

Fiddle Example here:

如何向 table 中的每一行添加点击事件,以便我可以将所点击行的 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)

只需将 click 处理程序添加到您的 <tr>:

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

并且在您的脚本中:

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

function doSomethingWithCountryId(countryId)
{
    // ...
}

查看更新Fiddle and Documentation