Have a Jquery selector that works, but does not work in $.post
I have this Jquery line which finds the cell I would like to input data into, This works when I use it outside of my $.post function (below), but not inside my $.post
$(this).parent().parent().find(".total_item_price").html("new text");
But when I use the above line in the below example, It does not work. It doesn't update the text in the required field.
$.post(url, { "params": value}, function(data) {
// This is where I am having a problem
// also tried .text and .val
$(this).parent().parent().find(".total_item_price").html(data.total_price_item);
alert(data.total_price_item); // This outputs my data
}, "JSON");
I basically want to开发者_StackOverflow put my returned (data) into the cell of the table. I don't think that my table structure is the issue, but I can post it if needed.
I should add, that I have to find the parents and field, because each post function will output into a different cell, so its relative to where the user clicked.
Whats going wrong in this code?
Because this
inside your load callback is not equal to this
outside of your load callback. They have different scopes.
Before you call the post, cache the this
from the other scope into a variable:
var scope = this;
And then in your callback you can reference the other this
as scope
:
$(scope).parent().parent().find(".total_item_price").html(data.total_price_item);
In $.post
this
will not point to the same element which you are thinking. Please use the actual selector to make it work.
because "this" in your function is a reference to the function and not to the node !
($this)
is not what you think it is! this
is always the owner of the function being executed, which in the $.post
is the callback function.
you can do it like this,
var a= $(this);
$.post(url, { "params": value}, function(data) {
// This is where I am having a problem
// also tried .text and .val
a.parent().parent().find(".total_item_price").html(data.total_price_item);
alert(data.total_price_item); // This outputs my data
}, "JSON");
$(this)
will not work there. As it is in the scope of the callback function, not the click event.
Assign $(this)
to a variable outside of the post (inside the click event handler) and then use that inside the post callback.
var that = $(this);
$.post(url, { "params": value}, function(data) {
that.parent().parent().find(".total_item_price").html(data.total_price_item);
alert(data.total_price_item); // This outputs my data
}, "JSON");
精彩评论