weixin_33724570 2018-04-01 02:13 采纳率: 0%
浏览 23

jQuery无法在浏览器中工作

This is my first time trying to work with JQuery and i am trying to deconstruct a piece of code i found online. It works in jsfiddle: JSFIDDLE. However, when i try to run the code in a browser, the part that is supposed to work when "create an account" is clicked, does not display. I have modified the code to work with the browser and it is as follows:

My index.html file:

<! DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

 <head>  
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript" src="script.js" ></script>
    <link rel="stylesheet" type="text/css" href="style.css"/>
 </head>

 <body>

 <div class="login-page">
 <div class="form">
   <form class="register-form">
     <input type="text" placeholder="name"/>
     <input type="password" placeholder="password"/>
     <input type="text" placeholder="email address"/>
     <button>create</button>
     <p id="message">Already registered? <a href="#">Sign In</a></p>
   </form>
   <form class="login-form">
     <input type="text" placeholder="username"/>
     <input type="password" placeholder="password"/>
     <button>login</button>
     <p id="message">Not registered? <a href="#">Create an account</a> </p>
   </form>
 </div>
 </div>
 </body> 

My script.js file:

$('.message a').click(function(){
   $('form').animate({height: "toggle", opacity: "toggle"}, "slow");
});

All the files are in the same directory. Any ideas on what might be wrong?

  • 写回答

2条回答 默认 最新

  • weixin_33701564 2018-04-01 02:15
    关注

    You're running the Javascript in the header, before the document has been fully parsed, so the handler you're adding isn't attaching to anything. Either give the script the defer attribute to force it to load once everything's been parsed:

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

    or put the script at the very bottom:

    <script type="text/javascript" src="script.js" ></script>
    </body>
    
    评论

报告相同问题?