gpt4 book ai didi

javascript - 添加到列表时会触发 Knockout JS 单击事件

转载 作者:行者123 更新时间:2023-11-30 15:36:53 25 4
gpt4 key购买 nike

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

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());

最佳答案

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

<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

关于javascript - 添加到列表时会触发 Knockout JS 单击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41400813/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com