I have an ajax function (not sure if relevant) that updates html and creates a few links:
<a href="#" class="clickme" onclick="column_click()" title="my title">click me</a>
I’m not sure why, but onclick, if I alert $(this).attr('title') it shows as undefined, and if I alert $(this) it shows [window]
function column_click(){
value = $(this);
console.log(value);
thetitle= $(this).attr('title');
console.log(thetitle);
}
Does anyone know why this is the case?
You’re confusing the obtrusive and unobtrusive styles of JS/jQuery event handling. In the unobtrusive style, you set up click handlers in the JavaScript itself, rather than in an
onclickattribute:The above will automatically bind
thisto the clicked element while the event is being handled.However, this is not standard JavaScript! It’s a feature of jQuery. The
onmethod is smart enough to bind the function to the HTML element when it handles the event.onclick="column_click"doesn’t do this, because it isn’t jQuery. It uses standard JS behavior, which is to bindthisto the global objectwindowby default.By the way, the reason you see
[window]is that$(this)has wrappedwindowin a jQuery object, so it looks like an array with thewindowobject inside it.There are three main ways to deal with your problem:
$('.clickme').on('click', column_click);in a script at the end of the page, or somewhere in the$(document).readyhandlerthismanually:onclick="column_click.call(this)"Avoid using
thisat all:Of these, I’d strongly recommend either 1 or 3 for the sake of good coding.