I have a function that dynamically creates div boxes and put an event on them. In the box I create an a-node and inside that an img-node. When I click the a-node the event shall fire and the background image shall be changed on another div. Below you can see my code, and as it it now, ‘this.src’ points to the a-node, which of course doesn’t work.
Is there a way to point at the a-node’s child, ie. the img-node on that line?
var box = $('<div/>', {
'class': 'imgDiv',
'width': maxWidth,
'height': maxHeight,
}).appendTo('.windowContent');
var a = $('<a/>', {
'href': '#',
}).appendTo(box)
var img = $('<img/>', {
'src': 'pics/' + this.fileName,
'width': this.thumbWidth,
'height': this.thumbHeight,
}).appendTo(a);
$(a).click(function() {
$('#desktop').css("background-image", "url(" + this.src + ")");
});
thiswill indeed point to the anchor that was clicked inside of the click handler. There’s nothing you can do about that, but your click handler will form a closure over yourimgvariable.Is this what you want?
EDIT
As Felix points out, a is already a jQuery object, so you can simply do: