How can I select parent element of $.ajax, or parent element of the element that triggered $.ajax. I need some kind of reference so I can apply result data to it:
var a = $a.val();
var b = $b.val();
$.ajax({
type: "POST",
url: "/Controller/Action",
data: { a: a, b: b },
success: function (data) {
var values = data.values,
$elements = $();
for (i = 0; i < 142; i++) {
$elements = $elements.add($("<div class='single'>").css('height', values[i]).css('margin-top', 26 - valuesG[i]));
}
//Here it should reference $(this).parent().parent().. something
//and not :last, because there are many .second elems...
//not only :last is being changed?
$elements.appendTo($(".second:last"));
$(".second:last").children(".single").addClass("ui-selected");
},
traditional: true
});
$(this).parent()
in ajax success function returns jQuery()
Any ideas?
How can I select parent element of $.ajax, or parent element of the element that triggered $.ajax. I need some kind of reference so I can apply result data to it:
var a = $a.val();
var b = $b.val();
$.ajax({
type: "POST",
url: "/Controller/Action",
data: { a: a, b: b },
success: function (data) {
var values = data.values,
$elements = $();
for (i = 0; i < 142; i++) {
$elements = $elements.add($("<div class='single'>").css('height', values[i]).css('margin-top', 26 - valuesG[i]));
}
//Here it should reference $(this).parent().parent().. something
//and not :last, because there are many .second elems...
//not only :last is being changed?
$elements.appendTo($(".second:last"));
$(".second:last").children(".single").addClass("ui-selected");
},
traditional: true
});
$(this).parent()
in ajax success function returns jQuery()
Any ideas?
3 Answers
Reset to default 6Use the context option:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
jQuery Reference
because by default ajax
call is asynch
and so when you do $(this)
inside success
the this
reference to ajax
api and so $(this).parent()
reference to jQuery()
.
to avoid this save the element
reference
in a variable
before ajax call starts to use inside success
.
target_element = $(this);
$.ajax({
type: "POST",
url: "/Controller/Action",
data: { a: a, b: b },
success: function (data) {
// ....................
target_element.parent()
...............................
Put the call to ajax in a function, and pass an element argument to the function?
function doAjax(triggerElement)
{
$.ajax({
url: whatever,
context: triggerElement,
success : function (content) { $(this).html(content); }
});
}
$(function () {
$('#triggerElementId').click(function () { doAjax(this); });
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745205277a4616564.html
评论列表(0条)