未捕获的TypeError:非法调用html / JS

时间:2018-02-26 06:56:36

标签: javascript html arrow-functions

问题: 一旦我将document.getElementById函数分配给变量然后调用它我得到上面的错误。完整代码如下 但是如果我将var $ docid = document.getElementById替换为var $ docid =(id)=>的document.getElementById(ID); html页面能够获取测验ID并将其呈现为正确的问题部分(无线电选择和输入文本等) 我提出这个问题的原因是因为这违背了javascript中的基本功能,即将函数分配给能够调用的变量。 document.getElementById()没有任何内容声称需要使用箭头功能。谁能解释一下?

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form id="get_quiz">
</form>
<br>
<form id="qbank">
</form>
<br>
<button type="submit" onclick="submit_quiz()">Submit Questions</button>
<button type="submit">Release Scores</button>
<button type="submit" onclick="add_question()">Add Question</button>
<button type="submit" onclick="view_qbank()">View Qbank</button>
</body>
<script>
var $docid = document.getElementById;
var x = 0;
function add_question() {
x++;
$docid('get_quiz').innerHTML += `
<h1>Question ${x}</h1>
<br>
<textarea id="${x}" rows=1 cols=100></textarea>
<br>
<p><strong>Constraints</strong></p>
<input type ='radio' id="if${x}"> If statement </input>
<input type ='radio' id="while${x}"> While Loop </input>
<input type ='radio' id="for${x}"> For Loop </input>
<br>
<br>
<input type = 'radio' id="easy${x}" name="difficulty">Easy </input>
<input type = 'radio' id="medium${x}" 
name="difficulty">Medium</input>
<input type = 'radio' id="hard${x}" name="difficulty">Hard</input>
<br>
<p><strong>Test Case</strong></p>
<input type="text" id="param${x}" placeholder="parameters"></input>
<input type="text" id="return${x}" placeholder="expected value">
</input>
`;
}

1 个答案:

答案 0 :(得分:3)

您的$docid方法不起作用,因为它没有正确的thisValue。 将document绑定到该方法将解决该问题:

var $docid = document.getElementById.bind(document);

有关this的更多信息:https://stackoverflow.com/a/3127440/4949918

相关问题