I've got the following jQuery expression, Inside the function I need a reference to the object that was clicked, is there a way to do this?
$('#tagList li').click(function() {
/* contents */
});
I've got the following jQuery expression, Inside the function I need a reference to the object that was clicked, is there a way to do this?
$('#tagList li').click(function() {
/* contents */
});
Yes, the this
keyword references the DOM element that was clicked. You can "wrap" it like this:
$(this)
This will allow you to treat it as a jQuery object.
The this keyword is what you are looking for. Often you will want to apply the jQuery function to this to do your job. Example:
$('#tagList li').click(function() {
$(this).css({ color: 'red' });
});
you can use the return value
$("#tagList li").bind("click", function(e) {
alert(e.currentTarget + ' was clicked!');
});
or if you want, you can simple point to the object in jQuery mode
$("#tagList li").bind("click", function(e) {
alert($(this) + ' was clicked!');
});
if you're new to jQuery, I strongly suggest you to see some screencasts from Remy Sharp in jQuery for Designers, they are great to understand a little bit of how jQuery works, and better yet, how to use the console.log() in order to see the objects that you can use!