如何将 Javascript 放在与 HTML 不同的文件中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32191226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:43:30  来源:igfitidea点击:

How to place Javascript in a separate file from HTML

javascripthtml

提问by Igors

I have this code placed in index.html, all together - Javascript and HTML. what I want is to place the JS into another, separate file called "pw.js".

我将这段代码放在 index.html 中,全部放在一起 - Javascript 和 HTML。我想要的是将 JS 放入另一个名为“pw.js”的单独文件中。

I have created a blank JS file located in folder "js". I have added it to (head) as well like this <script src="js/pw.js"></script>

我在文件夹“js”中创建了一个空白的 JS 文件。我也像这样将它添加到 (head) 中<script src="js/pw.js"></script>

This is what I have now in index.html, how to place the JS separatly? Please be specific in answers, I'm a beginner.

这就是我现在在 index.html 中的内容,如何单独放置 JS?请具体回答,我是初学者。

<script type="text/javascript">
  function isValid(){
    var password = document.getElementById('password').value;
    if (password == "123")
      top.location.href="./file.pdf";
    else
      {window.location.reload();}
  }
</script>

<div class="field_pw">
  <form name="PasswordField" action="">
    Password:
    <input type="password" id="password" name="password" class="noborder" style="font-size: 25px">
    <input type="button" class="button_pw" value="download" onclick="isValid();">
  </form>
</div>

采纳答案by Pepo_rasta

your pw.js file in js folder:

您在 js 文件夹中的 pw.js 文件:

function isValid() {
    var password = document.getElementById('password').value;
    if (password == "123")
        top.location.href="./file.pdf";
    else 
        window.location.reload();
}

your html file:

你的 html 文件:

<script type="text/javascript" src="js/pw.js"></script>
<div class="field_pw">
    <form name="PasswordField" action="">
        Password:
        <input type="password" id="password" name="password" class="noborder" style="font-size: 25px">
        <input type="button" class="button_pw" value="download" onclick="isValid();">
    </form>
</div>