javascript - 未捕获的类型错误 : Illegal invocation html/JS

标签 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>
`;
}

最佳答案

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

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

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

关于javascript - 未捕获的类型错误 : Illegal invocation html/JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48982970/

相关文章:

javascript - 这个 JS 是如何算出奇数或偶数的

javascript - Ember JS : Change path to access a route

javascript - 重置 Mapbox 中的所有标记层

javascript - 运行第一个 div onclick

javascript - 在 cshtml/razor 中使用 &lt;script src ="@microsoft/"问题

javascript - 如何使用箭头函数(公共(public)类字段)作为类方法?

javascript - 使用 Javascript 将光标自动移动到下一个表单域

javascript - 如何仅返回列表的单个值并将其添加到特定的 html 元素?

javascript - 滚动 div 并重新启用溢出后,焦点位于 div 时禁用正文滚动 :auto body scrolls

javascript - react : Handling Events - parameter visibility