我有一个简单的JSON结构,但我无法获得该页面的追加权。每个团队的所有名称都在一个选项标签中。它们应该在单独的选项标签中。
我搜索并阅读了一些类似的问题,但它们从来都不相似,我无法理解它们。
一旦我设法将它们单独附加,但后来有重复,我不知道如何解决重复问题。
PS:我认为我的追加结构不是最好的做法。我是JavaScript的新手,还不知道更好的方法。如果你有更好的解决方案,欢迎他们。
正确的HTML结构应为:
<fieldset class="team-wrap">
<label for="Team A"><img src='images/player1.png' alt="Team A">
<select name="Team A" id="Team A" multiple class="team dropdown selectpicker show-menu-arrow show-tick form-control" title="Players" data-width="70%" data-size="auto" multiple data-selected-text-format="count">
<optgroup label="Select a Player(s)">
<option value="Merv Jake">Merv Jake</option>
<option value="Derek Dax">Derek Dax</option>
<option value="Trace Harper">Trace Harper</option>
</optgroup>
</select>
</label>
</fieldset>
JSON:
{
"men": [{
"Team A": {
"img": "images/player1.png",
"names": ["Merv Jake", "Derek Dax", "Trace Harper"],
"group": "A"
},
"Team B": {
"img": "images/player2.png",
"names": ["Shannon Xavier", "Alec Xavier", "Simon Leslie"],
"group": "B"
}
}]
}
jQuery的:
function teams(gender){
var teams = $(".teams").find(".group");
$.getJSON('inc/miehet.json', function(data) {
$.each(data[gender], function(key, value) {
$.each(value, function(key) {
//console.log(key + " = " + this.img + " , " + this.names + " , " + this.group);
teams.append(
'<fieldset class="team-wrap">'+
'<label for='+key+'><img src='+this.img+' alt='+key+'>' +
'<select name='+key+' id='+key+' multiple class="team dropdown selectpicker show-menu-arrow show-tick form-control" title="Players" data-width="70%" data-size="auto" multiple data-selected-text-format="count">' +
'<optgroup label="Select a Player(s)">' +
'<option value="'+this.names+'">'+this.names+'</option>' +
'</optgroup>' +
'</select>' +
'</label>' +
'</fieldset>'
);
});
});
});
}
teams("men");
答案 0 :(得分:1)
根据@Barmar的评论,这对我有用:
http://codepen.io/stufu/pen/QNYdXV
function teams(gender){
var teams = $(".teams").find(".group");
$.getJSON('https://demo8858242.mockable.io/test', function(data) {
$.each(data[gender], function(key, value) {
$.each(value, function(key) {
teams.append(
'<fieldset class="team-wrap">'+
'<label for='+key+'><img src='+this.img+' alt='+key+'>' +
'<select name='+key+' id='+key+' multiple class="team dropdown selectpicker show-menu-arrow show-tick form-control" title="Players" data-width="70%" data-size="auto" multiple data-selected-text-format="count">' +
'<optgroup class="' + this.group + '" label="Select a Player(s)">' + '</optgroup>' +
'</select>' +
'</label>' +
'</fieldset>'
);
var group = $('.' + this.group);
$.each(this.names, function(key, name) {
group.append('<option value="'+name+'">'+name+'</option>');
});
});
});
});
}
teams("men");