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):
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.