如下图所示,我的单词“ es”和“ presso”被放在一个输入字段中,而不是在一个输入字段中是“ es”,在另一个输入字段中是“ presso”。
我的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"
}
}
这是我的循环的样子:
$.map(exercise, function(exercise, i) {
$("#addOpdracht").click();
$(".exerciseGetWordInput_" + i).val(exercise.word) // starts with 0
var exerSyll = json.main_object.main_object.exercises;
$.map(exerSyll, function(exer, s) {
console.log(exer.syllables);
$(".syllable" + s).val(exer.syllables);
});
});
放大我获取syllables
的循环:
var exerSyll = json.main_object.main_object.exercises;
$.map(exerSyll, function(exer, s) {
console.log(exer.syllables);
$(".syllable" + s).val(exer.syllables);
});
我创建syllable inputs
的函数:
function getWordPartInput(id, cValue){
cValue = cValue || '';
var wpInput = $('<input/>', {
'class': 'form-group form-control syllable' + SyllablesID++,
'type': 'text',
'value': cValue,
'placeholder': 'Syllables',
'name': 'Syllablescounter['+ SyllablesID++ +']'
});
return wpInput;
}
我做错了什么? (我确实声明了变量SyllablesID
,所以不用担心那部分。)
答案 0 :(得分:1)
var data = {
"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"
}
};
function draw(data){
for (ex of data.main_object.main_object.exercises){
for( sy of ex.syllables){
$("#container").append(`<input type="text" value="${sy}">`)
}
}
}
draw(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="container"><div>
syllables
是按照发布的JSON
的数组,因此您必须获取每个值并将其作为值添加到输入元素。您可以再次使用.map
或for/forEach
等循环遍历教学大纲数组并将数组条目添加到输入值中
$.map(exerSyll, function(exer, s) {
console.log(exer.syllables);
$.map(exer.syllables, function(syll, i){
$(".syllable" + i).val(syll);
})
});