Using $(this) within .get is undefined in jQuery
I'm using the shorthand AJAX call, $.get
but when I try and reference a variable with $(this)
, jQuery tells me that it's undefined.
Here is the block of code:
$('.replaceWithObject').live('click', function(event) {
var cid = $(this).find('input').val();
$.get('GetVideoComment.ashx?cid=' + cid, function(data) {
$(this).html(data);
});
});
It finds the cid
just fine, as $(t开发者_JS百科his)
is available prior to the $.get
. Inside the .get
$(this)
is undefined. Setting a var to $(this)
prior to the get
doesn't work either?
getVideoComment.ashx?cid=628
works, it returns a flash object. The issue is that $(this)
is undefined inside the get
.
Any idea on how to do what I want to do here? Or what I am doing wrong?
You need to cache your initial select so it exists when your callback fires.
$('.replaceWithObject').live('click', function(event) {
var $this = $(this);
var cid = $this.find('input').val();
$.get('GetVideoComment.ashx?cid=' + cid, function(data) {
$this.html(data);
});
});
Try this:
$('.replaceWithObject').live('click', function(event) {
var that = $(this);
var cid = that.find('input').val();
$.get('GetVideoComment.ashx', {'cid': cid}, function(data) {
that.html(data);
});
});
The problem is that this
inside of the get
function all is no longer .replaceWithObject
If you cache the this on the click event and use that cache then it will work for you.
As the returned data seems to be HTML, you could also just use load()
:
Load data from the server and place the returned HTML into the matched element.
$('.replaceWithObject').live('click', function(event) {
var cid = $(this).find('input').val();
$(this).load('GetVideoComment.ashx?cid=' + cid);
// or $(this).load('GetVideoComment.ashx', {cid: cid});
});
精彩评论