gpt4 book ai didi

javascript - 从 Knockout.JS 中的数组中删除特定元素

转载 作者:IT王子 更新时间:2023-10-29 03:09:12 25 4
gpt4 key购买 nike

我正在通过网络创建多人游戏,因此我必须对网络事件使用react。

我有这个简单的代码,但是 removePlayer 方法不起作用。 addPlayer() 工作正常。

<table id="userlist2" class="tablesorter" cellspacing="0">
<thead>
<tr>
<th>Name</th>
<th>Queue</th>
<th>Points</th>
</tr>
</thead>
<tbody data-bind="foreach: players">
<tr>
<td data-bind="text: name"></td>
<td data-bind="text: queue"></td>
<td data-bind="text: score"></td>
</tr>
</tbody>
</table>


function PlayerViewModel() {
var self = this;
self.players = ko.observableArray();

self.addPlayer = function (Name, QueuePos, Score) {
self.players.push({
name: Name,
queue: QueuePos,
score: Score
});
}


self.removePlayer = function (Name) {
for (var i = 0; i < self.players().length; i++) {

if (self.players()[i].name == Name) console.log(i);
self.players().splice(i, 1);
}
}
}


players = new PlayerViewModel();
ko.applyBindings(players);

players.addPlayer('Player1', '0', '0');
players.addPlayer('Player2', '0', '0');
players.removePlayer('Player2');

这是 http://jsfiddle.net/xseTc/

最佳答案

您必须使用 remove function :

self.removePlayer = function (Name) {
self.players.remove(function(player) {
return player.name == Name;
});

}

See fiddle

html

<table id="userlist2" class="tablesorter" cellspacing="0">
<thead>
<tr>
<th>Name</th>
<th>Queue</th>
<th>Points</th>
</tr>
</thead>
<tbody data-bind="foreach: players">
<tr>
<td data-bind="text: name"></td>
<td data-bind="text: queue"></td>
<td data-bind="text: score"></td>
</tr>
</tbody>
</table>

javascript

function PlayerViewModel() {
var self = this;

self.players = ko.observableArray();

self.addPlayer = function (Name, QueuePos, Score) {
self.players.push({
name: Name,
queue: QueuePos,
score: Score
});
}

self.removePlayer = function (Name) {
self.players.remove(function(player) {
return player.name == Name;
});
}
}

players = new PlayerViewModel();
ko.applyBindings(players);

players.addPlayer('Player1', '0', '0');
players.addPlayer('Player2', '0', '0');
players.removePlayer('Player2');

关于javascript - 从 Knockout.JS 中的数组中删除特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17630350/

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