将Javascript从html移到外部文件

Moving Javascript from the html to an external file

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

我在使用一些javascript时遇到了麻烦,我试图从内联转换为外部javascript文档。这段代码,我试图放在外部不起作用。

// JavaScript Document
function homepage() {
    $("#button").click(function(){
        $("#main, #nav").slideToggle();
        if($(this).html() == "-"){
            $(this).html("+");
            setTimeout(function() {
                $('#wrapper').css('top', 'auto');
                $('#wrapper').animate({ 'bottom': '0' }, 500);
            }, 500);
        } else {
            $(this).html("-");
            setTimeout(function() {
                $('#wrapper').animate({ 'top': '0' }, 500);
                $('#wrapper').css('bottom', 'auto');
            }, 500);
        }
    });
}

试图锁定脚本,因此:

$(document).ready(function(){
  // JavaScript Document
  function homepage() {
  $("#button").click(function(){
  $("#main, #nav").slideToggle();
  if($(this).html() == "-"){
      $(this).html("+");
      setTimeout(function() {
        $('#wrapper').css('top', 'auto');
        $('#wrapper').animate({ 'bottom': '0' }, 500);
      }, 500);
  }
  else{
      $(this).html("-");
      setTimeout(function() {
          $('#wrapper').animate({ 'top': '0' }, 500);
          $('#wrapper').css('bottom', 'auto');
      }, 500);
  }
  });}
});

我认为它"不起作用"是因为你的jQuery选择器失败了。把你的代码放在里面作为$(function () {...}),以确保它可以在dom上运行。

您的代码让我认为您正在使用jQuery。要将使用jQuery等库的JS文件移动到外部文件,必须执行以下步骤:

如果代码在jQuery内部,看起来像这样:

$(document).ready(function(){
    // here is all your code
});

然后你必须移动所有的,包括$(document).ready();部分到外部文件和(最好)加载它在你的html页面的底部。