Javascript 未捕获类型错误:无法读取属性';查询选择器';我做错了什么或错过了什么?
我有一个循环,它应该获取Javascript 未捕获类型错误:无法读取属性';查询选择器';我做错了什么或错过了什么?,javascript,jquery,Javascript,Jquery,我有一个循环,它应该获取单词和音节,但每当我这样做时,就会出现下一个错误: 未捕获的TypeError:无法读取null的属性“querySelector” 创建输入字段的代码: 在这个函数中,我的JSON应该附加word: function getWordInput(id, cValue) { cValue = cValue || ''; var wInput = $('<input/>', { 'class': 'exerciseGetWordIn
单词
和音节
,但每当我这样做时,就会出现下一个错误:
未捕获的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;
}
我的循环看起来如何:
$(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"
}
}
document.querySelector(
.word-${index})
在您的案例中未定义,我如何更改它,使其不会未定义/null?
{
"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"
}
}