简体   繁体   中英

jquery $(this).attr('href') returns undefined

I've got a very simple code

HTML

<a class="qqPopupCTA" href="http://example.com">Button</a>

JS

$qqPopupCTA = $('.qqPopupCTA');

function showForm(e){

    e.preventDefault();

    var targetPageUrl = $(this).attr('href');

    // do stuff
}

$qqPopupCTA.on('click', function(e){showForm(e);});

However I keep getting undefined href. Console.log($(this)) returns "window" and console.dir($(this)) returns "e.fn.init[1]"

Any idea what am I doing wrong? The code is super simple so I must be missing something obvious.

I think I've tried everything.

When you call showForm(e) , the context( this ) is not the anchor object inside showForm it is the window object.

So you can just pass the function reference as the click handler

$qqPopupCTA.on('click', showForm);

 $qqPopupCTA = $('.qqPopupCTA'); function showForm(e) { e.preventDefault(); var targetPageUrl = $(this).attr('href'); alert(targetPageUrl) // do stuff } $qqPopupCTA.on('click', showForm); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <a class="qqPopupCTA" href="http://example.com">Button</a> 

or pass a custom context to the showForm function using .call()

$qqPopupCTA.on('click', function (e) {
    showForm.call(this, e);
});

 $qqPopupCTA = $('.qqPopupCTA'); function showForm(e) { e.preventDefault(); var targetPageUrl = $(this).attr('href'); alert(targetPageUrl) // do stuff } $qqPopupCTA.on('click', function(e) { showForm.call(this, e) }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <a class="qqPopupCTA" href="http://example.com">Button</a> 

Try this:

$qqPopupCTA.on('click', showForm); // pass function name(ref) 

Or

$qqPopupCTA.on('click', function(e){
      showForm.call(this,e);
});

As per your approach this in the function setCurrent doesn't refers to the element which invoked the event. it is window object

Just pass function reference to when binding event

$qqPopupCTA.on('click', showForm);

OR, You can use bind()

$qqPopupCTA.on('click', function (e) {
    showForm.bind(this)(e);
});

The function showForm is defined globally , 'this' refers to window object . showForm(e,this) will give the reference of current element to the function.so passing the 'this' should fix your undefined this

$('.qqPopupCTA').on('click', function showForm() { var targetPageUrl = $(this).attr('href'); alert(targetPageUrl)

});

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