SelectedPlayers我正在使用jQuery模板的网站上做一些工作。
我有一个JSON对象:
var data = [{
"CoachingSessionActivityID": 1,
"PlayersInTeams": [{"PlayerID": 1, "PlayerName": "Some Name"},{"PlayerID": 2, "PlayerName": "Another Name"}],
"SelectedPlayers":[{"PlayerID": 1, "PlayerName": "Some Name"}]
},{
"CoachingSessionActivityID": 2,
"PlayersInTeams": [{"PlayerID": 1, "PlayerName": "Some Name"},{"PlayerID": 2, "PlayerName": "Another Name"}],
"SelectedPlayers":[{"PlayerID": 1, "PlayerName": "Some Name"}]
}];
如果当前迭代的PlayerID在选定的玩家对象中,我正在尝试将选择选项(由Bootstrap-Multiselect提供支持)标记为选中。
<select id="playersList_${CoachingSessionActivityID}" class="form-control players-list" multiple="multiple" name="playersList">
{{each(PlayerID, PlayerName) PlayersInTeams}}
{{if checkForValue(SelectedPlayers == PlayerID)}}
<option value="${PlayerID}" selected="selected">${PlayerName}</option>
{{else}}
<option value="${PlayerID}">${PlayerName}</option>
{{/if}}
{{/each}}
</select>
我正在使用此功能来识别玩家是否在所选列表中:
function checkForValue(json, value) {
for (key in json) {
if (typeof (json[key]) === "object") {
return checkForValue(json[key], value);
} else if (json[key] == value) {
return true;
}
}
return false;
}
问题
问题仅在于 1 项目被识别为选定值。我们的实际数据在“PlayersInTeams”中有150名玩家,一些教练会有超过20名选定的玩家。
有什么想法吗?
答案 0 :(得分:1)
我从这个答案中找到答案:https://stackoverflow.com/a/19302725/1888402
基本上使用具有以下功能的obj.some(...)
:
function hasValue(obj, key, value) {
return obj.hasOwnProperty(key) && obj[key] === value;
}
在问题的范围内,解决方案是:
{{each(PlayerID, PlayerName) PlayersInTeams}}
{{if SelectedPlayers.some(function(player){ return hasValue(player, "PlayerID", PlayerID)}) }}
<option value="${PlayerID}" selected="selected">${PlayerName}</option>
{{else}}
<option value="${PlayerID}">${PlayerName}</option>
{{/if}}
{{/each}}