在.get中使用$(this)在jQuery中是未定义的
我使用的是速记AJAX调用,在.get中使用$(this)在jQuery中是未定义的,jquery,scope,Jquery,Scope,我使用的是速记AJAX调用,$。get,但是当我尝试用$(this)引用变量时,jQuery告诉我它是未定义的 以下是代码块: $('.replaceWithObject').live('click', function(event) { var cid = $(this).find('input').val(); $.get('GetVideoComment.ashx?cid=' + cid, function(data) { $(this).html(data
$。get
,但是当我尝试用$(this)
引用变量时,jQuery告诉我它是未定义的
以下是代码块:
$('.replaceWithObject').live('click', function(event) {
var cid = $(this).find('input').val();
$.get('GetVideoComment.ashx?cid=' + cid, function(data) {
$(this).html(data);
});
});
它发现cid
很好,因为$(this)
在$之前可用。get
。在.get
$(此)
未定义。在get
之前将var设置为$(此)
也不起作用
getVideoComment.ashx?cid=628
工作时,返回一个flash对象。问题是$(this)
在get
中未定义
你知道我想在这里做什么吗?或者我做错了什么?您需要缓存初始选择,以便在启动回调时它存在
$('.replaceWithObject').live('click', function(event) {
var $this = $(this);
var cid = $this.find('input').val();
$.get('GetVideoComment.ashx?cid=' + cid, function(data) {
$this.html(data);
});
});
试试这个:
$('.replaceWithObject').live('click', function(event) {
var that = $(this);
var cid = that.find('input').val();
$.get('GetVideoComment.ashx', {'cid': cid}, function(data) {
that.html(data);
});
});
问题是这个函数中的get
函数不再是.replaceWithObject
如果您在单击事件上缓存此内容并使用该缓存,则它将对您有效。由于返回的数据似乎是HTML,您也可以使用:
从服务器加载数据,并将返回的HTML放入匹配的元素中
谢谢你。这是可行的,而且更有意义。但是我不明白为什么我不在这个范围之内。。。还是没有=(@Blankasaurus:this
是一个特殊变量,设置为对象,在上调用一个方法。您不是在元素上调用get()
,而是在jQuery
对象上调用。因此在回调中,this
不能设置为元素,因为它对它一无所知。
$('.replaceWithObject').live('click', function(event) {
var cid = $(this).find('input').val();
$(this).load('GetVideoComment.ashx?cid=' + cid);
// or $(this).load('GetVideoComment.ashx', {cid: cid});
});