I'm capturing all the clicks in my "a" elements with this:
$("a").click(function(e){....});
I want to know if it's possible to discard some events depending on some variable.
For example..
If href="http://www.google.es" then alert("google.es")
else if href="http://www.google.com" then do not handle the event and let the browser do whatever it has to do.
I don't know if I've explained it very well...
Or, you could do:
$("a[href!='http://www.google.com']").click(function(e) {
e.preventDefault();
if(this.getAttribute('href') === 'http://www.google.es') alert("google.es");
});
And not generate the click event for google.com
in the first place.
$("a").click(function(e){
e.preventDefault();
if (this.href == "http://www.google.es/") alert("google.es");
else if (this.href == "http://www.google.com/") window.location = this.href;
});
Fiddle Demo: http://jsfiddle.net/maniator/5XdkV/
Inside your function $(this).attr('href') should give you the href of the anchor tag - which you can then use in the rest of your logic
For your example above,
$('a[href*=.es]').click(function(e){
e.preventDefault();
});
Would make all links that contain .es in the href attribute to not be followed, but leaves the other links alone.
$("a").click(function(e) {
if ($(this).attr('href') == 'http://www.google.es') {
alert('google.es');
e.preventDefault();
}
// if code gets here, it's ok for the browser to handle normally.
}
All the suggestions posted so far will work, but they aren't the most flexible. If you want to match any link that has google.es
as the hostname, I'd do something like this:
$(document.body).delegate('a', 'click', function(e) {
var hostname = this.hostname || $(this).prop('href').split('/')[1];
if (hostname == 'www.google.es') {
alert('google.es');
e.preventDefault();
}
});
精彩评论