简体   繁体   中英

How to make all links on web page call javascript function?

I load different types of content through AJAX on my website.

I have a javascript function that will decide whether to open the link in an iframe or new tab based on the URL. But the question is how do I make all links call that javascript function?

I tried:

<base target= processurl()/>

Any ideas?

Thanks

EDIT: The JQUERY method works great. But it only works for one link? When I click a link the first time, it calls the function correctly. But any other links I click on after that, nothing happens.

using jQuery < 1.7:

$( 'a' ).live( 'click', function( ev ){
    ev.preventDefault(); // stop normal click on link

    // do stuff
} );

Note that jQuery 1.7 prefers the use of .on instead of .live :

$( document ).on( 'click', 'a', function( ev ){
    ....
} );

There are (at least) two ways you could approach this (depending on how it fits in with your Ajax code):

  1. Handle all clicks on the page with a common function that cancels the default click navigation and then subsitutes its own to load in iframe, new window, etc.
  2. Process all links on the page when the page loads, setting the target attribute as appropriate.

So the first way:

$(document).on("click", "a", function(e) {
   // stop default navigation
   e.preventDefault();

   // 'this' is the particular 'a' that was clicked
   var url = this.href;

   // process url somehow as desired to decide whether to open it
   // in new window, or iframe or to replace current page
});

Noting that the .on() method applies from jQuery version >= 1.7, so for older jQuery use the .delegate() method or for really old jQuery use the .live() method .

The second way (assumes links all exist when page is first loaded):

$(document).ready(function() {
    $("a").each(function() {
        var url = this.href;

        // process url somehow and set the target attribute as appropriate
        // e.g. for a new window
        this.target = "_blank";
        // or for an iframe
        this.target = "nameofiframe"
        // etc.
    });
});

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