对于这个问题,我深表歉意,但这是我用 javascript 编码的第 72 个小时,由于我不知道的原因,我找不到这个问题的答案。
我需要能够从外部 js 文件触发事件处理程序,如 onclick。这就是我在 HTML 中链接文件的方式。
<header>
<h1>McMac editing</h1>
<meta charset="utf-8">
<script src="JQuery.js"></script>
<script src="index.js"></script>
</header>
这就是我设置 index.js 的方式。
var capture = document.getElementById("capture");
capture.onload = function(){console.log="load";};
我最终会使用 cordova,它说内联 JS 被禁用,所以这就是我需要让它工作的原因,现在我的当前设置“加载”不会在我的控制台中弹出。
再次,我为这个问题道歉,但我不知道该怎么办。
最佳答案
当您应该使用此代码从 dom 获取它时,您正在尝试访问尚未加载的“捕获”元素var capture = document.getElementById("capture");
.In就在您编写的下一条语句 capture.onload = function(){}
。这会导致以下控制台错误,因为浏览器当时没有发现任何名为“capture”的元素存在,因此它将 null 对象返回给 捕获
。
Cannot set property 'onload' of null
你有两种方法来修复它
<强>1。 在 body 元素之后加载 index.js
<html>
.
.
</body>
<script src="index.js" type="text/javascript"></script>
</html>
<强>2。等到所有 body 元素都加载到 dom 中(不使用 JQuery)
document.addEventListener("DOMContentLoaded", function(event)
{
//Your code
var capture = document.getElementById("capture");
capture.onload = function()
{
console.log="load";
};
}
关于javascript - 从外部 js 文件触发 js 事件,如 onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37508010/