用Javascript为QCM动态生成问题——未捕获类型错误
Generate dynamically questions for QCM with Javascript -- Uncaught type error
我正在尝试用纯Javascript为QCM动态创建问题。用户按下"生成"按钮,就会出现带有答案的问题。我试着问了一个问题,但我得到了这个错误
未捕获的类型错误:未能在"节点"上执行"appendChild":参数1不是"节点"类型
我知道这个错误很常见,但我没有找到问题的答案。
Javascript代码:
var question = ["What is your favorite color ?:","red","white","green"];
function createQuestion(q,tag){
var q = [];
var tag = document.createElement("div");
tag.innerHTML = q ;
}
function generate(){
document.getElementsByTagName("body")[0].appendChild(createQuestion(question,"div"));
}
HTML只是:<button onclick = 'generate()'>generate</button>
这里的错误是什么?谢谢
您的错误是没有在createQuestion
函数中返回tag
。相反,它默认返回undefined
,这显然不是一个节点。
function createQuestion(q,tag){
var q = [];
var tag = document.createElement("div");
tag.innerHTML = q ;
return tag;
}
这样就可以返回您的标签。
编辑:
经过进一步检查,我发现了代码中的其他一些问题。这应该对你有用。
问题不再是一个简单的数组,因为更好地将答案和问题分开更有意义。
var item = {
question: 'What is your favourite color?:',
answers: ['red', 'white', 'green']
}
您当前的createQuestion
函数实际上没有多大意义。这个新元素的作用是创建一个元素,将另一个包含问题的元素放在其中,然后创建一个列表并用答案填充。
function createQuestion(qItem) {
var questionBox = document.createElement('div');
question = document.createElement('div');
question.innerHTML = qItem.question;
questionBox.appendChild(question);
var answers = document.createElement('ul');
for (var i= 0; i < qItem.answers.length; i++){
var answer = document.createElement('li');
answer.innerText = qItem.answers[i];
answers.appendChild(answer);
}
questionBox.appendChild(answers);
return questionBox;
}
function generate(){
document.getElementsByTagName("body")[0].appendChild(createQuestion(item));
}
相关文章:
- 为什么会出现错误;未捕获的类型错误:undefined不是函数;
- 同样,同样的错误'ahorcado.js:26未捕获类型错误:无法读取属性'beginPath'
- 未捕获的类型错误:无法读取属性'删除'的未定义
- 未捕获的类型错误:无法读取属性'name'即使它存在,也无法定义
- 看到“;未捕获的类型错误:无法读取属性'weight'未定义的“;尽管按照字面上的指示
- Soundcloud api"未捕获的类型错误:无法读取属性'uri'“未定义”;
- 未捕获的类型错误:无法读取属性'addEventListener'的null chrome扩展名
- 如何解决这种情况下的非法调用类型错误
- 未捕获的类型错误:$(..).dataTable不是函数
- 未捕获的类型错误:无法读取属性'状态'在react中为null
- 未捕获的类型错误:topFrame.window.changeSelectedBarStyle不是函数,原因是什么
- 类型错误:url未定义extjs 4正在填充组合框
- 未捕获的类型错误:无法读取属性'中止'的未定义
- 类型错误'未定义'不是对象(正在评估'navigator.connection.type'
- 未捕获的类型错误:无法设置属性'innerHTML'如果为null,则将脚本移动到正文不会;不起作用
- 未捕获的类型错误:undefined不是函数$
- 输入类型文件的未捕获类型错误
- 未捕获的类型错误:无法设置属性'背景'的未定义
- "未捕获类型错误/丢弃意外“;因为一句台词而出现?(HTML w/<脚本>)
- Javascript未捕获类型错误:无法读取属性'0'的未定义