我正在使用编辑按钮创建CMS。当您单击“编辑”按钮时,它应该从JSON文件回到CMS端,以便您可以进行实际编辑。
但是,当我尝试获取我的word
时,我只能在JSON中有2个word
时获取一个。
这是我的JSON的样子:
{
"main_object": {
"id": "new",
"getExerciseTitle": "TestToConfirm",
"language": "nl_NL",
"application": "lettergrepen",
"main_object": {
"title": "TestToConfirm",
"language": "nl_NL",
"exercises": [{
"word": "huishoudelijk",
"syllables": [
"huis",
"houdelijk",
"",
""
]
},
{
"word": "Kleedt u zich maar uit.",
"syllables": [
"Kleed",
"u",
"zich",
"uit"
]
}
]
},
"dataType": "json"
}
}
这就是我试图遍历word
的方式,以便我可以全部提取。我确实要注意,我也将要获取syllables
,但我不确定要创建两个不同的循环来获取数据是否不好。还是建议同时进行一次循环?
$(document).ready(function() {
$.getJSON('json_files/jsonData_' + ID + '.json', function(json) {
// console.log(json);
var exercisetitle = json.main_object.getExerciseTitle;
// console.log(exercisetitle);
$("#getExerciseTitle").val(exercisetitle);
var exercise = json.main_object.main_object.exercises;
$.map(exercise, function(exercise, i) {
var myindex = 1;
$("#addOpdracht").click();
$(".exerciseGetWordInput_" + myindex).val(exercise.word)
myindex++;
});
});
});
exerciseGetWordInput_
的代码:
#addOpdracht只是一个用于创建新练习块的按钮。我认为这与循环和我的应用失败的可能原因无关。
function getWordInput(id, cValue) {
cValue = cValue || '';
var wInput = $('<input/>', {
'class': 'exerciseGetWordInput_' + id + ' form-group form-control ExerciseGetWordInput',
'type': 'text',
'name': 'question_takeAudio_exerciseWord[' + exerciseAudioInput + ']',
'placeholder': 'Exercise',
'id': 'exerciseGetWordInput',
'required': true
});
return wInput;
}
答案 0 :(得分:1)
将var myindex = 1
移到循环之外
var myindex = 1;
$.map(exercise, function(exercise, i) {
$("#addOpdracht").click();
$(".exerciseGetWordInput_" + myindex).val(exercise.word)
myindex++;
});
或者您也可以避免像下面那样使用额外的变量,而改为使用each
$.each(exercise, function(exercise, i) {
$("#addOpdracht").click();
$(".exerciseGetWordInput_" + i).val(exercise.word) // starts with 0
});
答案 1 :(得分:0)
var data = {
"main_object": {
"id": "new",
"getExerciseTitle": "TestToConfirm",
"language": "nl_NL",
"application": "lettergrepen",
"main_object": {
"title": "TestToConfirm",
"language": "nl_NL",
"exercises": [{
"word": "huishoudelijk",
"syllables": [
"huis",
"houdelijk",
"",
""
]
},
{
"word": "Kleedt u zich maar uit.",
"syllables": [
"Kleed",
"u",
"zich",
"uit"
]
}
]
}
}
}
$.each(data.main_object.main_object.exercises, function(_,exercise) {
addOpdracht(exercise)
});
function addOpdracht(exercise) {
var $container = $("#exerciseContainer"),
count = $container.length,
$div = $("<div/>").addClass("exerciseDiv"),
$input = $("<input/>", {
type: "text",
id: "exerciseGetWordInput_" + count,
value: exercise.word
})
$div.append($input);
$container.append($div);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="exerciseContainer"></div>