我似乎无法遍历syllables
,而我对word
做的事情却完全相同。但是,这行得通,怎么办?
我的JSON:
{
"main_object": {
"id": "new",
"getExerciseTitle": "Example",
"language": "nl_NL",
"application": "lettergrepen",
"main_object": {
"title": "Example",
"language": "nl_NL",
"exercises": [{
"word": "espresso",
"syllables": [
"es",
"presso",
"",
""
]
}]
},
"dataType": "json"
}
}
我的syllables
循环:
var exerSyll = json.main_object.main_object.exercises;
$.map(exerSyll, function(exerSyll, s) {
$(".syllable" + s).val(exercise.syllables)
});
我的word
循环确实有效:
var exercise = json.main_object.main_object.exercises;
$.map(exercise, function(exercise, i) {
$("#addOpdracht").click();
$(".exerciseGetWordInput_" + i).val(exercise.word)
});
应该在其中附加syllables
的地方:
function getWordPartInput(id, cValue){
cValue = cValue || '';
var wpInput = $('<input/>', {
'class': 'form-group form-control syllable',
'type': 'text',
'value': cValue,
'placeholder': 'Syllables',
'name': 'Syllablescounter['+ SyllablesID++ +']'
});
return wpInput;
}
是否可以创建一个循环并将syllables
附加在音节输入中,并将word
附加在练习输入中?还是必须是单独的循环?当我将其取回CMS时,我希望将所需的syllables
保留为正确的word
。
答案 0 :(得分:3)
您的问题是,您在const melissaBirthdayParty = new Date();
let birthdayPartyTime = melissaBirthdayParty.getTimezoneOffset();
console.log("The party is at " + birthdayPartyTime)
函数回调中使用exerSyll
,因此它提升了原始声明的map
变量,这就是为什么在其中获得exerSyll
的原因您的代码:
Ecxeption
您应在回调函数中对变量使用另一个名称,以避免发生异常。
//First declaration of exerSyll
var exerSyll = json.main_object.main_object.exercises;
//Reusing the same variable exerSyll in the callback
$.map(exerSyll, function(exerSyll, s) {
//Will cause an exception beacause exerSyll declaration will be hoisted
$(".syllable" + s).val(exercise.syllables)
});
演示:
这是一个有效的演示,显示了问题的解决方案。
var exerSyll = json.main_object.main_object.exercises;
$.map(exerSyll, function(exer, s) {
console.log(exer.syllables)
});
var json = {
"main_object": {
"id": "new",
"getExerciseTitle": "Example",
"language": "nl_NL",
"application": "lettergrepen",
"main_object": {
"title": "Example",
"language": "nl_NL",
"exercises": [{
"word": "espresso",
"syllables": [
"es",
"presso",
"",
""
]
}]
},
"dataType": "json"
}
};
var exerSyll = json.main_object.main_object.exercises;
$.map(exerSyll, function(exer, s) {
console.log(exer.syllables)
});