user5393067
user5393067

Reputation:

JQuery anchor link event handler does not work with "this"

Why this code does not display href link

$("a.cliRedir").click(function() {
    alert($("this").attr('href'))
});

Upvotes: 0

Views: 47

Answers (4)

Aakash
Aakash

Reputation: 1791

Use this without double quotes.

$("a.cliRedir").click(function() {
    alert($(this).attr('href'))
});

Upvotes: 0

Joydeep
Joydeep

Reputation: 76

try

$(document).ready(function(){
  $('a').click(function(){
      alert($(this).attr('href'));
  });
});

In you code you are missing semi-colon at alert.

Upvotes: 0

madalinivascu
madalinivascu

Reputation: 32354

try:

$('body').on('click','a.cliRedir',function(e) {
    e.preventDefault();
    alert($(this).attr('href'))
});

Upvotes: 0

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

Because you are using "this" string. Your code now actually searches for an HTML tag named <this></this> which is senseless.

this is an object and it should be:

$("a.cliRedir").click(function() {
    alert($(this).attr('href'))
});

Another important point is that you do not need jQuery to get the href, and it is a good idea to use vanilla JS when it is possible, since it improves readbility and performance:

$("a.cliRedir").click(function() {
    alert(this.href);
});

Upvotes: 1

Related Questions