使用Knockout嵌套表

时间:2015-05-21 16:03:58

标签: javascript jquery html knockout.js

我有一张桌子,我想在点击时在tr下面显示一个tr。 它工作正常,但我想让第二个tr嵌套在一个表中。但是,当我把它放在一个表中时,它无法显示。

    <table class="table table-striped">
    <thead>
    <tr>
        <th>Id</th>
        <th>First name</th>
        <th>Last name</th>
        <th>Email</th>
    </tr>
    </thead>
    <tbody data-bind="foreach: customers">
    <tr data-bind="click: $root.viewCustomerDetails">
        <td data-bind="text: id"></td>
        <td data-bind="text: first_name"></td>
        <td data-bind="text: last_name"></td>
        <td data-bind="text: email"></td>
    </tr>
    <tr data-bind="attr: {id: $data.id}, style: {color: 'red', display: 'none'}">
        <table>
            <tr>
                <td data-bind="text: $data.address"></td>
                <td data-bind="text: $data.last_logon"></td>
                <td data-bind="text: $data.telephone"></td>
                <td data-bind="text: $data.fraud"></td>
            </tr>
        </table>
    </tr>
</table>
</tbody>
</table>

和Js:

self.viewCustomerDetails = function(i, e){
                var row = $('#' + i.id());
                $('#' + i.id()).toggle();
            }
        };

1 个答案:

答案 0 :(得分:4)

你不需要jQuery来做这件事。您可以执行以下操作:

<tbody data-bind="foreach: customers">
    <tr data-bind="click: $root.viewCustomerDetails">
        <td data-bind="text: id"></td>
        <td data-bind="text: first_name"></td>
        <td data-bind="text: last_name"></td>
        <td data-bind="text: email"></td>
    </tr>
    <tr data-bind="visible: showDetails">
       <td colspan="4">
           <table>
                <tr>
                   <td data-bind="text: address"></td>
                   <td data-bind="text: last_logon"></td>
                   <td data-bind="text: telephone"></td>
                   <td data-bind="text: fraud"></td>
                </tr>
            </table>
        </td>
    </tr>
</tbody>

JS:

function Customer () {
   var self = this;
   //your properties id, first_name, last_name
   self.showDetails = ko.observable(false);
}

function CustomersViewModel() {
   var self = this;
   //your observableArrays, that contains a collection of Customer, declared above
   self.viewCustomerDetails = function (customer) {
       customer.showDetails(!customer.showDetails());
   }
}

ko.applyBindings(new CustomersViewModel());