【问题标题】:Knockout JS click event fires when adding to list添加到列表时会触发 Knockout JS 点击事件
【发布时间】:2016-12-30 18:19:37
【问题描述】:

我希望能够通过单击列表中的名称从可观察数组中删除一个项目。但是,我注意到每次将项目添加到表或列表时都会触发 click 事件。就我而言,我希望能够单击列表中的某个项目以将其删除,但是将删除绑定到单击事件将始终导致前一个项目被删除。有没有办法在不使用点击事件的情况下做到这一点?下面,我将包含一个 jsFiddle,它是演示该问题的淘汰教程的略微修改版本。

https://jsfiddle.net/hardrock302/93wdcm65/

代码如下:

    <h2>Your seat reservations</h2>

<table>
<thead><tr>
    <th>Passenger name</th><th>Meal</th><th>Surcharge</th><th></th>
</tr></thead>
<!-- Todo: Generate table body -->
<tbody data-bind="foreach: seats">
<tr>
<td data-bind="text:name, click:alert('test')"></td>
</tr>
</tbody>
</table>

// Class to represent a row in the seat reservations grid
 function SeatReservation(name, initialMeal) {
var self = this;
self.name = name;
self.meal = ko.observable(initialMeal);
}

// Overall viewmodel for this screen, along with initial state
function ReservationsViewModel()     {
var self = this;

// Non-editable catalog data - would come from the server
self.availableMeals = [
    { mealName: "Standard (sandwich)", price: 0 },
    { mealName: "Premium (lobster)", price: 34.95 },
    { mealName: "Ultimate (whole zebra)", price: 290 }
];    

// Editable data
self.seats = ko.observableArray([
    new SeatReservation("Steve", self.availableMeals[0]),
    new SeatReservation("Bert", self.availableMeals[0])
]);
}

ko.applyBindings(new ReservationsViewModel());

【问题讨论】:

    标签: javascript knockout.js


    【解决方案1】:

    一个匿名函数会为你解决这个问题:

    <td data-bind="text:name, click: function(data, event) { alert('test')}"></td>
    

    有关此页面的更多信息:http://knockoutjs.com/documentation/click-binding.html#note-2-accessing-the-event-object-or-passing-more-parameters

    【讨论】:

    • 另外,您可以使用punches plugin&lt;button type="button" data-bind="on.click: x = x + 1"&gt;Increment&lt;/button&gt;
    猜你喜欢
    • 1970-01-01
    • 2018-04-18
    • 1970-01-01
    • 1970-01-01
    • 2013-07-31
    • 2020-12-27
    • 1970-01-01
    • 2020-03-02
    相关资源
    最近更新 更多