2009-05-17 45 views
0

我想要获取jquery ajax回调函数来更新表格单元格的背景颜色,但我无法使其工作。jQuery - 无法在ajax回调函数中设置css propery

我有以下代码(产生在Firebug没有错误):

$(".tariffdate").click(function() { 
    var property_id = $('#property_id').attr("value"); 
    var tariff_id = $('#tariff_id').attr("value"); 
    var tariff_date = $(this).attr("id"); 
    $.post("/admin/properties/my_properties/booking/edit/*", { property_id: property_id, tariff_id: tariff_id, tariff_date: tariff_date }, 
function(data){ 
    var bgcol = '#' + data; 
    $(this).css('background-color',bgcol); 
    alert("Color Me: " + bgcol); 
}); 

我已经添加了警报只是为了确认我收到预期的数据传回(6位十六进制代码)我是 - 但我的表格单元格的背景固执地拒绝改变。

所有表格单元格都有.tariffdate类,但也有单独的ID。

作为一个测试,我想为类创建一个悬停功能:

$(".tariffdate").hover(function() { 
    $(this).css('background-color','#ff0000'); 
}); 

以上正常工作 - 所以我,为什么我的回调函数不能正常工作真的很困惑。有任何想法吗?

回答

2

在AJAX完成处理程序中,this的实例更改为ajax对象。您需要将this的实例保存到一个对象并使用该对象。例如:

$(".tariffdate").click(function() { 
    var property_id = $('#property_id').attr("value"); 
    var tariff_id = $('#tariff_id').attr("value"); 
    var tariff_date = $(this).attr("id"); 
    var tariff = $(this); 
    $.post("/admin/properties/my_properties/booking/edit/*", 
     { property_id: property_id, tariff_id: tariff_id, tariff_date: tariff_date }, 
     function(data) { 
     var bgcol = '#' + data; 
     tariff.css('background-color',bgcol); 
     alert("Color Me: " + bgcol); 
     } 
    ); 
}); 
+0

你是明星 - 那是问题所在。谢谢! – BrynJ 2009-05-17 17:49:55

1

检查你的ajax回调函数中的“this”变量是什么。我怀疑这不是指.tariffdate