简体   繁体   English

将javascript放入外部文件并从中调用函数

[英]taking javascript into an external file and calling a function from it

I have made a working webpage but when i try to take the jscript into an external file it no longer is called. 我已经制作了一个正常工作的网页,但是当我尝试将jscript放入外部文件时,它不再被调用。 i have put in the code in my header to include the file name but still unable to call it. 我已在标题中放入代码以包含文件名,但仍然无法调用它。 Here is my jscript please help me out by the way just a quick edit I got the isMobile function from here http://www.abeautifulsite.net/blog/2011/11/detecting-mobile-devices-with-javascript/ 这是我的jscript,请通过快速编辑的方式帮助我,我从这里获得了isMobile函数http://www.abeautifulsite.net/blog/2011/11/detecting-mobile-devices-with-javascript/

<script>        
    var isMobile = {
      Android: function() {
        return navigator.userAgent.match(/Android/i);
      },
      BlackBerry: function() {
        return navigator.userAgent.match(/BlackBerry/i);
      },
      iOS: function() {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i);
      },
      Opera: function() {
        return navigator.userAgent.match(/Opera Mini/i);
      },
      Windows: function() {
        return navigator.userAgent.match(/IEMobile/i);
      },
      any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
      }
    };
    function load()
    {
      var w=((screen.availWidth)/50)*49;
      var h=(w/4)*3;
      if( isMobile.any() ){
        var t=w;
        w=h;
        h=t;

      }
      var a=document.getElementById('banner');
      a.style.width=w+'px';
      a.style.height=(h/4)+'px';
      var b=document.getElementById('main');
      b.style.width=w+'px';
      b.style.height=Math.round((h/7)*4)+'px';
    }
  </script>

When referencing an external JavaScript file, its contents should not be surrounded by a <script> tag. 引用外部JavaScript文件时,其内容不应包含<script>标记。 The <script> tag in the main file is what informs the browser that the contents should be parsed as JavaScript. 主文件中的<script>标记告知浏览器应将内容解析为JavaScript。 Remove the surrounding <script> tag from the external file. 从外部文件中删除周围的<script>标记。

Proper reference in the main file: 主文件中的正确参考:

<script type='text/javascript' src='path/to/external.js'></script>

The language='JavaScript' attribute has been deprecated and is unnecessary. language='JavaScript'属性已被弃用 ,不必要。 You may include type='text/javascript' . 您可以包括type='text/javascript'

The contents of the external file should contain only JavaScript code, not surrounding <script> tags as in: 外部文件的内容应包含JavaScript代码,而不包含<script>标记,如下所示:

// File external.js
alert('Look, no script tag!');

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

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