Manu P Manu P - 8 months ago 32
jQuery Question

jQuery : "this" property is not working on $(document) click

I want to change my clicked image src. I tried it using

this
. The reason is I am using
$(document)
for click function. The code I am using is shown below. It will change without using
this
property. But I need to work it using
this
property.

$document.on('click', 'img.flagImg', function () {
_flag();
})
var _flag = (function(){
$(this).attr('src',"images/flag.jpg")
})


but its not getting. can any one suggest another option for getting a good solution.

Answer Source

When you call a function like that, _flag(), this is set to the global object (in loose mode) or undefined (in strict mode).

Just let jQuery set this for you:

$document.on('click', 'img.flagImg', _flag);

But if you want to avoid jQuery passing it the event argument, you can use call to set this explicitly instead:

$document.on('click', 'img.flagImg', function() {
    _flag.call(this);
});