每个循环的JS knockout都会产生新的id

时间:2013-02-27 10:35:27

标签: knockout.js foreach

我已经获得了一个Knockout js foreach循环,该表返回多个用户,并为每个返回的用户搜索该记录的搜索按钮。按钮和数据按原样绘制,但是当我单击任何搜索按钮时,它只返回第一个用户。我相信这是因为搜索按钮的id始终是相同的,需要与DOM交互以添加每个函数?这是否正确,如果是这样,这是怎么做的?

    

    <!-- ko foreach: $data -->
    <table class="table table-striped, table-bordered" id="customer-results-policy">
        <thead>
            <tr>
                <th>
                    Title
                </th>
                <th>
                    First Name
                </th>
                <th>
                    Surname
                </th>
                <th>
                    Date of birth
                </th>
                <th>
                    Email
                </th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>
                    <span data-bind="text: Customer.Title"></span>
                </td>
                <td>
                    <span data-bind="text: Customer.Forename"></span>
                </td>
                <td>
                    <span data-bind="text: Customer.Surname"></span>
                </td>
                <td>
                    <span data-bind="dateString: Customer.DateOfBirth"></span>
                </td>
                <td>
                    <div><input type="text" id="email-search-box-customer" class="span3 search-query" readonly="readonly" data-bind="value: Customer.Email"  /> <br/>
                    <button type="submit" data-bind="click: $parent." class="btn btn-primary submit-email-search-customer">Search for this customer</button>  </div>

                </td>
            </tr>
        </tbody>
    </table>
    <!-- /ko -->

JS

$(&#39;#page-parent&#39;)。on(&#39;点击&#39;,&#39; .submit-email-search-customer&#39;,function(){< / p>

        $('.submit-email-search-customer').each(function() {
        });

        var email = $('#email-search-box-customer').val();

        var dataExists;
        {
            dataExists = viewModel.refreshViewByEmail(email);
        }

        if (!dataExists) {
            $('#error-message').html("<strong>The email address wasn't recognised -- please check and try again</strong>");
            $('#error-display').show('slow');
            return false;
        } else {
            $('#search-results-many').hide();
            $('#customer-results-email').show();
            $("#search-results").show('slow');
            $("#modify-button").show('slow');
            $("#customer-modify").show();
            $("#account-results").show();
            $("#address-results").show();

        }

1 个答案:

答案 0 :(得分:1)

首先,你不能将常量值用作foreach中的id,因为这将使你的html具有多个具有相同id的元素(不允许)

因为您正在使用knockout来管理您的模板,所以我应该使用knockout click绑定来管理点击事件。请参阅淘汰赛的文档 http://knockoutjs.com/documentation/click-binding.html