简体   繁体   English

function 已定义但从未使用

[英]function is defined but never used

I am having trouble reloading the page.我在重新加载页面时遇到问题。 I tried to use JavaScript in Vue by adding this code我尝试通过添加此代码在 Vue 中使用 JavaScript

<body onload="myFunction()">

function myFunction() {
   window.location.reload()
}

This error is poppng up:弹出此错误:

 74:10  error  'myFunction' is defined but never used  no-unused-vars

Any suggestions?有什么建议么?

no-unused-vars is a ESLint warning. no-unused-vars是 ESLint 警告。 It occurs because you don't call your function anywhere in your javascript code, and ESLint cannot read that it is being called from an HTML attribute.发生这种情况是因为您没有在 javascript 代码中的任何地方调用 function,并且 ESLint 无法读取它是从 HTML 属性调用的。

You can turn off this warning like this:您可以像这样关闭此警告:

<script>
/* eslint-disable no-unused-vars */
function myFunction() {
  window.location.reload()
}
/* eslint-enable no-unused-vars */
</script>

Although calling javascript functions from HTML attributes is not good practice today.尽管从 HTML 属性调用 javascript 函数在今天并不是很好的做法。

There is a javascript way to wait for the load event, instead of using onload attribute:有一种 javascript 等待加载事件的方法,而不是使用onload属性:

<script>
function myFunction() {
  window.location.reload()
}

document.addEventListener('DOMContentLoaded', myFunction);
</script>

Regarding the comment on the page reload only once.关于页面上的评论只重新加载一次。 You can keep the fact that the page has been reloaded in the localStorage :您可以保留页面已在localStorage中重新加载的事实:

<script>
function myFunction() {
  // Check that the page has not been reloaded
  if (localStorage.getItem('reloaded') === null) {
    // Save the fact that we are reloading the page, and reload page
    localStorage.setItem('reloaded', true);
    window.location.reload();
  } else {
    // Otherwise, reset the flag so that on the fresh load the page can be reloaded again
    localStorage.removeItem('reloaded');
  }
}

document.addEventListener('DOMContentLoaded', myFunction);
</script>

please use script tag for function or any javascript related code.请为 function 或任何 javascript 相关代码使用脚本标签。

<body onload="myFunction()">

<script type='text/javascript' charset='UTF-8'>
     function myFunction() {
          window.location.reload()
     }
</script>

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

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