我有一个应该获取word
和syllables
的循环,但是每次这样做,我都会收到下一个错误:
未捕获的TypeError:无法读取null的属性'querySelector'
我在其中创建输入字段的代码:
在此函数中,我的JSON应该附加word
:
function getWordInput(id, cValue) {
cValue = cValue || '';
var wInput = $('<input/>', {
'class': 'exerciseGetWordInput_' + id + ' form-group form-control ExerciseGetWordInput word',
'type': 'text',
'name': 'question_takeAudio_exerciseWord[' + exerciseAudioInput + ']',
'placeholder': 'Exercise',
'id': 'exerciseGetWordInput',
'required': true
});
return wInput;
}
在第二部分中,我的JSON应该附加syllables
:
// This is the function that creates the syllable inputs.
function getWordPartInput(id, cValue) {
cValue = cValue || '';
var wpInput = $('<input/>', {
'class': 'form-group form-control syllable syl ' + TT++,
'type': 'text',
'value': cValue,
'placeholder': 'Syllables',
'name': 'Syllablescounter[' + SyllablesID++ + ']'
});
return wpInput;
}
我的循环如下:
$(document).ready(function() {
$.getJSON('json_files/jsonData_' + ID + '.json', function(json) {
//loops through the words and fetches them back to the CMS side.
var exercise = json.main_object.main_object.exercises;
exercise.forEach((exercise, index) => {
const word = exercise.word; // should grab the word
const syls = exercise.syllables; // Grab the syllables array
const container = document.querySelector(`.word-${index}`); // Get the correct container based on our index(index)
container.querySelector('.word').value = word; // Assign the word to the first input
// Foreach syllable
syls.forEach((syl, i) => {
container.querySelectorAll('.syl')[i].value = syls; // Assign the syllable to the correct input based on our index(i)
});
});
});
});
不确定是否需要这样做,但是如果您想查看我的JSON:
{
"main_object":{
"id":"new",
"getExerciseTitle":"Example",
"language":"nl_NL",
"application":"lettergrepen",
"main_object":{
"title":"Example",
"language":"nl_NL",
"exercises":[
{
"word":"Example",
"syllables":[
"Example1",
"Example2",
"",
""
]
}
]
},
"dataType":"json"
}
}