$(document).ready(function() { $("...">

Suppress <a> href anchor tag when using jquery

I have the following code:

  <script type="text/javascript">

  $(document).ready(function() 
  {
    $("#thang").load("http://www.yahoo.com");

    $(".SmoothLink").click( function()
    {
      $("#thang").fadeOut();

      $("#thang").load($(this).attr("href"));           

      $("#thang").fadeIn();

    });
  });

  </script>

  <a href="http://www.google.com" id="thelink" class="SmoothLink">click here</a><br /><br />
  <div style="border: 1px solid blue;" id="thang">
  </div>

What I'm trying to achieve is a quick and easy ajax-ify way on a site by simply placing the class on specific links that I want to load in a div. The problem I am facing is that the normal anchor action is triggered and just redirected to the href link normally. How to suppress normal anchor action?

+3
source share
2 answers

Generally:

$('a').click(function(e) {
    //prevent the 'following' behaviour of hyperlinks by preventing the default action
    e.preventDefault();

    //do stuff

});

or

$('a').click(function(e) {
    //do stuff

    //equivalent to e.preventDefault AND e.stopPropagation()
    return false;
});

Additional Information:

http://docs.jquery.com/Events/jQuery.Event#event.preventDefault.28.29

The previous question is about the difference between return falseand e.preventDefault():

event.preventDefault () vs. return false

+8

, ...

$("#thang").fadeOut();
$("#thang").load($(this).attr("href"));
$("#thang").fadeIn();

... jQuery , :

$("#thang").fadeOut().load($(this).attr("href")).fadeIn();
+1

Source: https://habr.com/ru/post/1719061/


All Articles