简体   繁体   中英

How to avoid page refreshing on anchor (<a></a>) tag click?

I'm creating a dynamic website. My problem is when i click on the following tag:

<a class="s-inte" href="set_interesantes.php?n=Frank Melo&u=f6e79cfe9c0ecc4c08dac4c860c4802b&back=http://localhost:8085/Something/success/profile.php?search_user=f6e79cfe9c0ecc4c08dac4c860c4802b&p=12&sa=f6e79cfe9c0ecc4c08dac4c860c4802b&i=2345123&dl=&iv=1">Interesante</a>

The page gets refreshed, How do I avoid this page refresh?

What you want to accomplish is to update some counter of interestings w/o refreshing the page? You should do it using AJAX techniques, this is what AJAX was invented for.

Consider the following code, it's top easy (jQuery library required):

<a href="#" class="counter">Interesante</a>

<script>
$(function(){
    $("a.counter").click(function()
    {
         $.get("set_interesantes.php?n=Frank Melo&u=f6e79cfe9c0ecc4c08dac4c860c4802b&back=http://localhost:8085/Something/success/profile.php?search_user=f6e79cfe9c0ecc4c08dac4c860c4802b&p=12&sa=f6e79cfe9c0ecc4c08dac4c860c4802b&i=2345123&dl=&iv=1" );
         .... // you can do some animation here, like a "Liked!" popup or something
         return false; // prevent default browser refresh on "#" link
    });
});
</script>

you need to prevent default action on the click event.

You can do a simple inline handler which will return false

<a class="s-inte" onclick="return false" href="set_interesantes.php?n=Frank Melo&u=f6e79cfe9c0ecc4c08dac4c860c4802b&back=http://localhost:8085/Something/success/profile.php?search_user=f6e79cfe9c0ecc4c08dac4c860c4802b&p=12&sa=f6e79cfe9c0ecc4c08dac4c860c4802b&i=2345123&dl=&iv=1">Interesante</a>

or write a jQuery handler which will do the same

$('.s-inte').click(function(e){
    e.preventDefault()
})

If you are dynamically loading the content using ajax. You should probably call it in this way. This way it will work for every anchor with .s-inte class, no matter it's added dynamically or statically.

$(document).on('click', '.s-inte',function(e){
    e.preventDefault();

    // Do more stuff every anchor click here...
});

put href="javascript:void(0)"

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