【问题标题】:jQuery tmpl if object value == current iteration valuejQuery tmpl if object value == 当前迭代值
【发布时间】:2015-07-22 18:32:33
【问题描述】:

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 名选定球员。

有什么想法吗?

【问题讨论】:

  • 因为你在条件为真时结束函数操作。你需要迭代完整的列表。为什么你调用与链相同的函数?
  • 不应该 {{if checkForValue(SelectedPlayers == PlayerID)}}{{if checkForValue(SelectedPlayers, PlayerID)}} 否则它会将布尔值传递给函数?
  • 对不起,你是对的 Ishettyl ,我正在这样做。我只是侵入了我的代码以删除敏感数据,却忘记为帖子修复它。这是一个很好的观点@ARUNRAJ

标签: javascript jquery jquery-templates


【解决方案1】:

@Arunraj 是对的,我的函数显然在返回 true 时结束,因此它没有迭代完整列表。

我从这个答案中找到了答案: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}}

【讨论】:

    猜你喜欢
    • 2011-04-14
    • 2013-03-05
    • 1970-01-01
    • 2016-04-09
    • 1970-01-01
    • 1970-01-01
    • 2011-06-28
    • 1970-01-01
    • 2012-04-12
    相关资源
    最近更新 更多