繁体   English   中英

为什么我无法从 HTML 文件中访问 javascript function?

[英]Why can't I access javascript function from HTML file?

这里相当基本的问题。 我遇到了一种情况,我似乎无法从我的 HTML 文件中访问 Javascript 函数,即使我已将 JS 文件链接为脚本 src。 这似乎是一个非常简单的问题,但我无法弄清楚问题是什么。

我正在尝试将名为startLogin的 function 添加到 HTML 按钮。 我将其添加为onclick ,但是当我尝试单击按钮时,控制台显示 function 未定义。 然而,function 在 JS 文件中明确定义,据我所知,我用于onclick的语法和script src链接是正确的。

此外,我已经确认 JS 文件链接到 HTML 文件。 如果我尝试从 JS 文件中操作 DOM 只是为了做一些简单的事情,比如将背景设置为红色,那效果很好。 问题是当我尝试调用 JS 文件中定义的 function 时。 此外,我确保我尝试调用的 function 确实有效。 如果我将它正确粘贴在脚本标签内的 HTML 文件中,它就可以正常工作。

我已经尝试将脚本标签移动到 HTML 末尾的正文中,因为我知道这通常是问题,但在这种情况下它不起作用。 谁能帮我确定为什么我无法从 HTML 按钮访问“startLogin”function?

仅供参考,这是一个 javascript 项目,我正在使用 Vite.js 进行捆绑。 我项目中的所有其他 HTML/JS 文件都很好地配合在一起,我只是在登录页面上有问题。

文件结构:

|-pages
  |-login.html
  |-login.js

登录.html

 <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial- 
    scale=1.0" />
    <title>Document</title>

    <!-- LINK JS FILE -->
    <!-- MODULE TYPE IS RELATED TO VITE.JS -->
    <script type="module" src="./login.js"></script>

  </head>

  <body>
    <!-- email login form -->
    <form name="emailLogin" id="emailLogin" style="display: none">
      <div class="row" style="width: 600px">
        <div class="col">
          <div class="form-row" style="padding-bottom: 10px">
            <input
              type="email"
              class="form-control"
              id="emailAddress"
              placeholder="email associated with your login"
              style="width: 576px"
            />
          </div>
        </div>
        <div class="form-row">
          <br />
          <button type="button" class="btn btn-primary" onclick="startLogin('email')">
            Send Email Login
          </button>
        </div>
      </div>
    </form>
  </body>
</html>

登录.js

// start the login process by generating a code sent either SMS or EMAIL
      function startLogin(login_type) {

        // local variables
        var ajaxResult;
        var subs;
        var tempString;

        // get the login values and set up the call
        if (login_type == "phone") {
          // get the values
          use_country_code = $("#country").val();
          use_phone = $("#phoneNumber").val();
          use_phone = use_phone.replace(/\D/g, "");

          // do the validation
          if (use_phone.length < 10) {
            $("#errorText").html(
              "Phone number doesn't have enough digits, please try again."
            );
            $("#errorModal").modal("show");
            return;
          }

          // build the url
          post_url =
            "https://us-central1-dev-api-327415.cloudfunctions.net/user-login?cc=" +
            use_country_code +
            "&phone=" +
            use_phone;
        } else {
          // get the values
          use_email = $("#emailAddress").val();

          // do the validation
          if (!validateEmail(use_email)) {
            $("#errorText").html(
              "Email address does not appear to be valid, please check the format and try again."
            );
            $("#errorModal").modal("show");
            return;
          }

          // build the url
          post_url =
            "https://us-central1-dev-api-327415.cloudfunctions.net/user-login?email=" +
            use_email;
        }

        // send the request to the server and process the results
        $.LoadingOverlay("show");
        $.ajax({
          type: "POST",
          url: post_url,

          // process the returned result of the Ajax call
          success: function (ajaxResult) {
            // see if we have a session token and handle the response
            session_token = ajaxResult["session_token"];
            if (session_token == "None") {
              // hide the login and show the text message area if phone, otherwise hide email and show email message
              if (login_type == "phone") {
                $("#loginMethod").hide();
                $("#phoneLogin").hide();
                $("#codeLogin").show();
                $("#loginMessage").hide();
                $("#textMessage").show();
              } else {
                $("#loginMethod").hide();
                $("#emailLogin").hide();
                $("#loginMessage").hide();
                $("#codeLogin").show();
                $("#emailMessage").show();
              }
            } else {
              // hide everything since already logged in and show the right message
              $("#phoneLogin").hide();
              $("#emailLogin").hide();
              $("#loginMethod").hide();
              $("#loginMessage").hide();
              $("#codeLogin").hide();
              $("#continueLoginAlready").show();
            }
          },

          // process after the Ajax call has been fully completed
          complete: function () {
            $.LoadingOverlay("hide");
          },

          // handle total failure
          error: function (jqXHR, exception) {
            console.log(jqXHR);
            console.log(exception);
            json_error = jqXHR["responseJSON"];
            $("#errorText").html(json_error.error_message);
            $("#errorModal").modal("show");
          },
        });
      }

Javascript 模块的工作方式略有不同。 在那里,变量和函数不会暴露给全局 scope。

如果你想从代码的其他部分使用你的 function,你必须在window object 上明确设置它:

function startLogin(...) {
...
}
window.startLogin = startLogin;

另一种解决方案是将 js 设置在 html 的末尾,而不是您不需要使用 window object(内存滞后)

<html lang="en">
  <head>...</head>
  <body>
    <button type="button" id="myButton">Title</button>
  </body>
  <script>

    function myFunction(){
      console.log('running myFunction');
    }

    const button = document.querySelector('#myButton');
    
    button.addEventListener('click', function clickListener(
    {
      myFunction();
    }
  </script>
</html>

浏览器简直是愚蠢的,它会从上到下加载页面,如果您在所有 html 出现后加载您的 js,您可以这样做。

暂无
暂无

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

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