我有一个数据对象,我用它来动态更新使用jQuery的选择下拉列表。该代码对于该对象的一个孩子来说非常好,但对于另一个孩子来说它根本不起作用。
我的HTML:
<form name='apwd_player_reg' class='apwd_ctm_reg_form'>
<div id='existing_player_selector' class='apwd_form_fragment'>
<label for='existing_player_type'>Player Type</label>
<fieldset>
<input type="radio" name="existing_player_type" value="jun" />Junior
<input type="radio" name="existing_player_type" value="sen" />Senior
</fieldset>
<label for='existing_team'>Existing Team</label>
<select name='existing_team' id='existing_team'>
<option value='0'>Find your current team...</option>
</select>
<label for='player_name'>Player</label>
<select name='player_name' id='player_name'>
<option value='0'>Select player...</option>
</select>
</div>
</form>
我的JS,包括对象:
var teamData = {
"sen": {
"Thunder": {
"237": "Aaron Peachey",
"357": "Dave Smith",
"687": "Gareth Stevens"
},
"Feeders": {
"231": "Craig Bell",
"563": "Homer Simpson",
"134": "Javal McGee"
}
},
"jun": {
"U12 Magic": {
"5": "Ayden Jones",
"17": "Jake Peterson",
"13": "Nick Mee"
},
"U10 Thunder": {
"5": "Katie Simpson",
"17": "Billy Jones",
"13": "Tim Smith"
}
}
};
var team_select = jQuery("#existing_team");
var player_select = jQuery("#player_name");
var player_type = jQuery("input[type=radio][name=existing_player_type]");
var reg_type = jQuery("input[type=radio][name=reg_type]");
var teams = null;
var players = null;
//populate team names from junior vs senior selection
player_type.on('change', function() {
team_select.empty();
team_select.append(jQuery("<option value='0'>Your current team...</option>"));
teams = teamData[jQuery(this).val()];
jQuery.each(teams, function(key) {
team_select.append(jQuery("<option></option>")
.attr("value", key).text(key));
});
});
//populate team names from junior vs senior selection
team_select.on('change', function() {
player_select.empty();
player_select.append(jQuery("<option value='0'>Player name...</option>"));
var player = player_type.val();
var team = jQuery(this).val();
players = teamData[player][team];
jQuery.each(players, function(key, value) {
player_select.append(jQuery("<option></option>")
.attr("value", key).text(value));
});
});
你可以在我的jsfiddle中看到:
https://jsfiddle.net/aaronp/21vuLru3/
如果选择初级单选按钮,则会填充团队列表。从这里开始,如果您选择一个团队,它会正确填充播放器列表。这适用于两个初级团队。 如果选择高级单选按钮,它也会正确填充团队列表。但是从这里开始,如果您选择一个团队,除了默认选项之外,它不会在播放器列表中填充任何内容。当我在console.log(播放器)之后在代码中查找它的对象是返回undefined。我不明白它是如何找不到高级球队的任何球员但是他们发现他们对于初级球队来说很好。
我尝试更改对象中的项目顺序,更改标签和团队名称等,但此特定对象始终无法检索任何结果。
有什么想法吗?
由于 亚伦
答案 0 :(得分:0)
您的播放器选择器在team_select.on('change', function() {...}
而不是:
var player = player_type.val();
使用:
var player = $('input[name= existing_player_type]:checked', '#existing_player_selector').val();
它应该工作。 (然后你可以随意重构它)
这是一个有效的JsFiddle: https://jsfiddle.net/21vuLru3/3/
祝你好运, 埃里克