简体   繁体   中英

JQuery trigger anchor's onclick event without sending browser to href

I want to have an a tag with an href and an onclick function, but when the user clicks the link I don't want the browser to go to the href but just execute the onclick . I tried the following:

 function testFunc() { document.getElementById("testDiv").innerHTML = "it works!"; } $('.testClass').click(function(event) { $(this).trigger("onclick"); event.preventDefault(); }); 
 <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script> <a href="http://www.google.com" class="testClass" onclick="testFunc()">click me</a> <div id="testDiv"></div> 

  • Note: while it appears to work in the snippet editor, in a full page the browser does go to Google.

You don´t need all that, just adding return false to your onclick handler would work:

 function testFunc() { document.getElementById("testDiv").innerHTML = "it works!"; return false; } 
 <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script> <a href="http://www.google.com" class="testClass" onclick="testFunc()">click me</a> <div id="testDiv"></div> 

Your problem is taht you trigger click two times , first when clicking the element then when clicking happened so you should put other function inside the fist one after preventing default . Use event.preventDefault();

I replaced this line <a href="http://www.google.com" class="testClass" onclick="testFunc()">click me</a> with this <a href="http://www.google.com" class="testClass" >click me</a> then modified script

 function testFunc() { document.getElementById("testDiv").innerHTML = "it works!"; } $('.testClass').click(function(event) { event.preventDefault(); testFunc(); }); 
 <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script> <a href="http://www.google.com" class="testClass">click me</a> <div id="testDiv"></div> 

Put it like this :

 <html>
 <head>
 <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script> 


 </head>
 <body>

<a href="http://www.google.com" class="testClass">click me</a> 

<div id="testDiv"></div>
<script>
  function testFunc() {
    document.getElementById("testDiv").innerHTML = "it works!";
  }

  $('.testClass').click(function(event) {
    event.preventDefault();
    testFunc();

  });
   </script>
 </body>
</html>

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