简体   繁体   English

Function 在 onload 事件后不可访问。 “类型错误:{someFunctionName} 不是函数”

[英]Function is not accessible after onload event. "TypeError: {someFunctionName} is not a function"

I have written a small and simple slider with Javascript. Because I want to be sure that the slider works when I load the javascript in the footer of the page.我用 Javascript 写了一个小而简单的 slider。因为我想确保在页面底部加载 javascript 时 slider 工作。 I added an onload event and copied the whole slider application inside the event.我添加了一个onload事件并将整个 slider 应用程序复制到该事件中。 In the HTML I unfortunately have an inline onclick element in a tag.在 HTML 中,不幸的是我在标签中有一个内联onclick元素。 But since I have the code inside the onload scope the onclick doesn't work anymore.但是由于我在 onload scope 中有代码,所以 onclick 不再起作用。 My idea is not to bind the event inline in the html but directly in the javascript. That should work.我的想法不是在 html 中内联绑定事件,而是直接在 javascript 中绑定事件。这应该可行。 But I am also interested if it is possible to do it with the inline onclick.但我也很感兴趣是否可以使用内联 onclick 来做到这一点。

Question What do I have to do so that the onclick element addresses the corresponding function within the onclick function?问题我必须做什么才能使 onclick 元素寻址 onclick function 中相应的onclick

 document.querySelector('body').onload = function() { function init() { //... } const f2 = function() { //... } init(); /* that will work */ const anchorPrev = document.querySelector('.prev'); anchorPrev.addEventListener('click', () => { console.log('prev'); }); /* My question */ function next() { console.log('next') } };
 a { cursor: pointer; }
 <body> <a class="next" onclick="next()">next (I'm curious to know if it works??)</a><br/> <a class="prev">prev (Will work)</a> </body>

Two issues:两个问题:

  1. It's better to wait for the DOMContentLoaded event on the window object.最好等待window object 上的DOMContentLoaded事件。
  2. You're defining the function within the scope of the function, so it's not globally accessible.您在 function 的 scope 中定义了 function,因此它不可全局访问。 This means that the onclick can't see the function. Use a let variable, then set the function inside the listener callback like this:这意味着onclick看不到 function。使用let变量,然后在侦听器回调中设置 function,如下所示:

 <button onclick="log()">click me</button> <script> let log; window.addEventListener('DOMContentLoaded', () => { console.log('loaded'); log = () => console.log('clicked'); }); </script>

You can add that the onload event = function next()您可以添加 onload 事件 = function next()

JavaSript code: Java脚本代码:

document.querySelector('body').onload = function() { 

  const a = document.querySelector('a')
  a.onclick = function next() {
    event.preventDefault()
    console.log('next')
  }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM