将内联JS更改为外部

change inline JS to external

本文关键字:外部 JS      更新时间:2023-09-26

我想将html底部的这个内联javascript更改为external.js文件。它会根据鼠标是否在其上来更改图像大小。我想知道我是否必须更改下面的代码,或者我是否错误地调用了css元素。

<SCRIPT LANGUAGE="JavaScript">
    $('img').hover(function(){
        $(this).css({width:"100%",height:"100%"});
    },function(){
        $(this).css({width:"50%",height:"50%"});   
    });
</SCRIPT>

我要感谢所有对我的问题投反对票的人;作为一个初学者,当我问这个问题时(现在仍然是),你让我在这里感到温暖和舒适,让我失去了信心。

您将有一个单独的文件,以这种方式从HTML文档中引用

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

那个文件只包含你的实际代码

$('img').hover(function(){
    $(this).css({width:"100%",height:"100%"});
},function(){
    $(this).css({width:"50%",height:"50%"});   
});

您可能还需要将javascript放入文档就绪调用-中

$(function(){
  $('img').hover(function(){
      $(this).css({width:"100%",height:"100%"});
  },function(){
      $(this).css({width:"50%",height:"50%"});   
  });
});

其他资源

  • https://softwareengineering.stackexchange.com/questions/91242/what-is-the-best-way-to-include-javascript-file-using-script-tag
  • 我什么时候应该使用内联和外部Javascript
  • http://api.jquery.com/ready/

您的脚本看起来不错。要从外部文件中包含它,您只需要创建一个新的.js文件,该文件只包含<script>标记之间的文本。。。并包括如下内容:

<script src="path/file.js">

很好,您可以毫无问题地将其移动到自己的文件中,然后用以下标记替换脚本标记:

<script type="text/javascript" src="/path/to/your/external/js" />

我不得不添加"$(document).ready(function(){",它开始工作。

$(document).ready(function(){
    $('img').hover(function(){
        $(this).css({width:"100%",height:"100%"});
    },function(){
        $(this).css({width:"50px",height:"50px"});   
    });
});`