Reputation: 13
Apologies if this is a stupid beginners question, but I'm stuck.
I have some jquery code to get some HTML from the server, which I then wish to paste in a provided div. The div is set as data-target. So I use the $($(this).attr('data-target'))
context to find the target div. However in the .done()
function, I'm no longer in the context and I can't find the target div.
$('.popout-button').click(function (event) {
event.preventDefault();
targetElem = $($(this).attr('data-target'));
//request
$.get("ajax.php", {
action: "defInfo",
class: "Cats22"
})
.done(function (data) {
//Dump the data
//This doesn't work. Can I pass targetElem somehow?
targetElem.html(data);
});
});
Upvotes: 1
Views: 116
Reputation: 37701
If you want to avoid dealing with the scopes and access the element from a lower level, you can add an id to your element, or, if you can't (for whatever the reason), you can add a class name dynamically... like this:
$($(this).attr('data-target')).addClass('target');
Then, just select it again within the done() function like this:
var targetElem = $('.target');
targetElem.html(data);
Upvotes: 0
Reputation: 8251
If you declare your targetElem
at global level i.e. out side the function and then initialize it then I think it will work i.e. you can access it from inside the done
function
var targetElem;
$('.popout-button').click(function(event) {
event.preventDefault();
targetElem = $($(this).attr('data-target'));
//request
$.get("ajax.php", {action: "defInfo", class: "Cats22"})
.done(function(data) {
//Dump the data
//This doesn't work. Can I pass targetElem somehow?
targetElem.html(data);
});
});
Upvotes: 1