想象一下:
$('#blah').on('click', function(){
var cat_id = $(this).attr('id');
$.ajax({
// stuff...
data: {cat_id: cat_id}, // <--------------------
// stuff...
}).done(function(){
alert(cat_id); // <-------------------- not defined...
});
});
如您所知,jQuery已弃用之前的$.ajax
使用类型,新模式如上所示,在done()
函数的上述代码中,我如何访问cat_id
?
在done()函数中$(this)
不再被识别,cat_id
也不被识别......
在jQuery引入done()
之前,我们可以轻松访问已发送的数据,因为我们使用的是success:
,我们仍然可以通过ajax函数访问发送的数据。
答案 0 :(得分:1)
我无法复制您所写的行为,但是如果您需要在done函数中访问jQuery(this),您可以执行以下操作:
$('#blah').on('click', function(){
var cat_id = $(this).attr('id');
var $self = $(this);
$.ajax({
// stuff...
data: {cat_id: cat_id},
// stuff...
}).done(function(){
alert($self.attr('id'));
});
});
答案 1 :(得分:1)
在您的示例中,您仍然可以访问done函数中的cat_id,因为它仍在范围内。如果你需要访问$(this),你需要将它绑定到完成的回调,如下所示:
$('#blah').on('click', function(){
var cat_id = $(this).attr('id');
$.ajax({
// stuff...
data: {cat_id: cat_id}, // <--------------------
// stuff...
}).done(function(){
alert(cat_id); // alerts 'blah'
alert($(this).attr('id')); // also alerts 'blah'
}.bind(this)); // NOTICE THIS
});
答案 2 :(得分:0)
虽然这可能是一种解决方法,但你可以这样做......
将cat_id存储在 $(this).data(“catId”)中,然后轻松访问它。 所以你可以相应地轻松处理多个事件。
快乐编码:)
答案 3 :(得分:0)
你可以尝试使用闭包的功能,这应该有效:
var cat_id = $(this).attr('id');
var done_handler = function(){
alert(cat_id);
};
$.ajax({
// stuff...
data: {cat_id: cat_id}, // <--------------------
// stuff...
}).done(done_handler);