简体   繁体   中英

When I click on button, nothing happens

I have following HTML ,

 $(document).ready(function() { $('#searchMovieBtn').click(function(e) { e.preventDefault(); console.log('search'); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="searchMovieBtnBox"> <button class="btn btn-primary" type="button" id="searchMovieBtn">Search</button> </div>

When I click on button, nothing happens, it seems like event is not triggering.

It is a caching issue. When you was developing and testing your JQuery code, your old code remained into the browser cache. Browser cached it to load page faster in next uses. In order to solve this problem you have 3 options.

  1. Delete your browser history
  2. Refresh your browser by pressing Ctrl + F5 (Preferred for developing purpose)
  3. Tell browser that this JQuery code has changed by adding a version for it. It is used when you are publishing your code on the server because you can't ask your clients to delete their browser history or load your page by pressing Ctrl + F5

Here is how you could add version to your JQuery code:

<script type="text/javascript" src="js/script.js?v=1"></script>

Look at v=1 . Next time when you updated your JQuery code change it to v=2 to tell browser that your code has been changed.

You can try the next thing,

First of all, your HTML markup I think it might be wrong as you are not pointing out correctly the folders. I attached all the css and js bootstrap + jquery files through a CDN.

<!DOCTYPE html>
 <html>
   <head>
   <meta charset="utf-8">
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
   <script 
    src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"</script>
    <script type="text/javascript" src="js/script.js"></script>
    <link rel="stylesheet" 
 href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <title> jQuery button click event working?</title>
</head>
<body>
  <div id="searchMovieBtnBox">
    <button class="btn btn-primary" type="button" id="searchMovieBtn">Search</button>
  </div>
  </body>
 </html>

Therefore,your script.js stays as it is. For me it has worked like this. I got the message printed onto my console. Hope that helps you.

在此处输入图片说明

确保 HTML 中没有其他具有相同 id 的元素。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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