Html 将 html5 中的 javascript 放在外部文件中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15896704/
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-29 07:22:01  来源:igfitidea点击:

place javascript in html5 in external file

javascripthtml

提问by jagguy

In html5 how do i place the class below (constructor and method)in another file and reference it in the html file.

在 html5 中,我如何将下面的类(构造函数和方法)放在另一个文件中并在 html 文件中引用它。

Below I have everything in 1 file and I dont want that.

下面我将所有内容都放在 1 个文件中,但我不想要那个。

  <canvas id="myCanvas" width="600" height="400"></canvas>
<script>
  var canvas = document.getElementById('myCanvas');
  var ctx = canvas.getContext('2d');
  ctx.font="14px Arial"; 



  //how to move to other file
  function ClassPerson(gender,name1) {
      var aa;
      this.gender=gender;
      this.name1=name1;
      aa=6;

  };

   //how to move to other file
  ClassPerson.prototype.m_sayGender = function()
    {
    ctx.fillText("this gender= " + this.gender + " gender=" + this.name1,10,40);
    };

    //stay in this file
  var person1 = new ClassPerson('male','dave');
  var person2 = new ClassPerson('female','bet');
  ctx.fillText("this gender= " + person1.gender,10,20);
  person1.m_sayGender();
  myObject._three();

</script>

回答by Jacob

You simply create an external JS file with your code and include it like this:

您只需使用您的代码创建一个外部 JS 文件并像这样包含它:

<script src="myFile.js"> </script>or

<script src="myFile.js"> </script>或者

<script src="<myFile>.js" type="text/javascript"></script>

Be sure to place the JS file in the directory where you have your HTML file

请务必将 JS 文件放在您拥有 HTML 文件的目录中

After comment: I guess you have to dynamically create an image with javacript set it's srcporpertie and the diplay it.

评论后:我想您必须使用 javacript 动态创建一个图像,将其设置为 porpertiesrc并显示它。

回答by Andy

Set the whole JS code of your class in an external *.js file. Then import it into your *.html file like this:

在外部 *.js 文件中设置类的整个 JS 代码。然后将其导入到您的 *.html 文件中,如下所示:

<script src="<external-file-name>.js" type="text/javascript"></script>