When using jquery, I have frequently made use of $(this) within events, functions, etc.
Recently I tried the following:
function btn_edit_click (event) {
alert(event.data.idnum);
}
$(".btn_edit").on("click", { idnum: $(this).attr("title") }, btn_edit_click);
For some reason I get the title of the entire PAGE, rather than the element(s) being referenced by $(".btn_edit"). Am I doing something wrong, or is this expected behaviour?
Well it depends what this code is nested within. If the answer is nothing then
thisrefers to thewindowobject.If you were referring to
thisinside an event handler thenthiswould refer to the element on which the event triggered. But it appears as though you are usingthisin the global space.If you want the title of the
.btn_editelement to be accessible in the callback function just refer tothisin your callback function (notice how it simplifies your code as well):Here is a demo: http://jsfiddle.net/gRK3z/
Also here is a performance test to show the difference between using
.attr('title')and.title: http://jsperf.com/jquery-attr-title-vs-title