js中遇到的一個小問題,關於Uncaught ReferenceError:XXX is not defined at HTMLAnchorElement.onclick報錯

1、報錯代碼及緣由javascript

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <a href="javascript:void(0)" onclick="init()">點我</a>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script type="text/javascript">
    //var init;
 window.onload=function(){ var init = function(){ console.log(0) } } </script>
</html>

一、或者吧init函數寫在JQ的$(document).ready函數裏面也會報標題錯誤;緣由是未找到該函數;html

2、爲何會報錯?java

  一、具體緣由應該是和html渲染過程有關。這裏就不詳細說;總之就是點擊的時候當即執行,發現該函數還未定義。因此就報錯了;jquery

    二、解決辦法:一個是直接寫函數,不謝window.onload函數或者JQ的ready方法。但推薦第二個方法,以下:ajax

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <a href="javascript:void(0)" onclick="init()">點我</a>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script type="text/javascript">
    var init;      //先聲明一個變量,後面再給其賦值 window.onload=function(){ var init = function(){ console.log(0) } } </script>
</html>
相關文章
相關標籤/搜索