簡體   English   中英

如何在每個表行上放置click事件並將結果作為參數傳遞,以將新數據綁定到另一個源?

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

我有以下代碼,該代碼填充一個select options ,並將選定的值傳遞給視圖模型中的另一個函數,該模型用匹配選定值的數據填充一個表:

簡而言之,如果用戶從選擇選項中選擇了ASIA,則ASIA中的所有國家/地區都將綁定到該表:

小提琴示例在這里:

如何在表中點擊事件添加到每一行,這樣我可以通過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)
{
    // ...
}

查看更新的小提琴文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM