How to connect both onclick () and href to the <a> element but have only one job at a time

I have an element like this:

<a class='link' href='/page1'>Page 1</a>

This click handler has this:

$('.link').click(function() { loadPage('page1'); });

Clicking a link loads a new page. However, there are two options for loading a new page. One of them is through AJAX, which determines which elements have been changed between pages and reloads sections without updating based on this, and one of them loaded using a regular GET request.

I would like to set the href URL links for regular downloads and onlick () to call the javascript function that does the AJAX download. However, they both shoot when I click the link, leaving the page completely refreshed.

Is there a way to prevent the use of "href" when using Javascript?

+3
source share
4 answers
$('.link').click(function() { loadPage('page1'); return false });

or

$('.link').click(function(e) { e.preventDefault(); loadPage('page1'); });

Firstly, the bubble also stops. Secondly, just prevent ... the default action (*, which follows the link)

+7
source

Return falsefrom the onclick handler.

+3
source

You can do it

<a class='link' href='/page1'>Page 1</a>

$('.link').click(function(e) { 
e.preventDefault(); // Prevents the default action, i.e. following the href
loadPage('page1'); 
});
0
source

A brief description of the problem (the difference between return false;and e.preventDefault();) is here . It may also be required e.stopPropagation();, especially because loadPage () throws an error (as Ben Roe noted).

0
source

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


All Articles