Hello all. I'm trying to use the 'this' keyword to work with jQuery. I'm trying to rotate an image when it's clicked by passing 'this' as a parameter in it's onclick function. How would I then reference the image using jQuery?
before passing the anonymous function to your click handler, do
var self = this;
and change the references to this
in your handler to self
See http://stackoverflow.com/questions/962033/what-underlies-this-javascript-idiom-var-self-this/962040#962040 For an example in the question.
To quote:
function Note() {
var self = this;
var note = document.createElement('div');
note.className = 'note';
note.addEventListener('mousedown', function(e) { return self.onMouseDown(e) }, false);
note.addEventListener('click', function() { return self.onNoteClick() }, false);
this.note = note;
// ...
}
basically, when the event handler actually calls the function, the context has changed -- this
no longer refers to the same object you thought it did. We get around this by using a non-special variable name, self
which the function retains visibility of due to closure.
If you pass the element (this) through to a function via onclick, you can just wrap the jQuery function ($) around it to treat it like a jQuery object.
<script type="text/javascript">
function myfunction(img) {
var el = $(img);
// Some other code
}
</script>
<img src="someimage.jpg" alt="" onclick="myfunction(this)" />
To reference the image clicked and change it's src-attribute you do like this:
$(document).ready(function() {
$("img").click(function() {
var $this = $(this); //For performance
$this.attr("src","NewImgSrc.jpg");
});
});