2012-07-03 33 views
0

我想我需要在基于Ajax返回的元素上进行简单的css更改时遇到'this'作用域的问题。当单击元素时将jQuery选择器应用到表格

$('.time_slot_holder').click(function(){ 
    var data_day=$(this).data('agent_day'); 
    var data_time=$(this).data('agent_time'); 
    var data="agent_id="+agent_id+"&day="+data_day+"&time="+data_time 
    $.ajax({ 
     type:"POST", 
     url:"admin_includes/book_time.php", 
     data:data, 
     success:function(html){ 
      var split_html=html.split("|") 
      if(split_html[0]=="B"){ 
       //booking exists 
       alert("Bookings for this time slot exist. Contact Agent to arrange a re-assignment of this appointmnet."); 
      } 
      if(split_html[0]=="C"){ 
       //added to db 
       $(this, '.time_slot_holder').css('background-color', 'red'); 
      } 
      if(split_html[0]=="D"){ 

      } 
     } 
    });//end ajax 
}); 

所有我试图做的是改变颜色与要素网格.time_slot_holder

忽略来自Ajax请求,这只是一个尝试通过数据属性标识元素的笨拙分割回调。基本上我需要将clicked元素的引用传递给ajax的回调函数。

+0

可能重复(http://stackoverflow.com/questions/1392789/jquery- ajax-call-this-does-not-work-success-success) – Matt

回答

1

您应该将AJAX请求中的context选项设置为this;

$.ajax({ 
    type:"POST", 
    url:"admin_includes/book_time.php", 
    context: this, 
    //.. 
}); 

否则,this最终被所述jqXHR对象。

另一种(更常见的)方法是将this的值存储在另一个变量中;

var that = this; 

$.ajax({ 
    type:"POST", 
    url:"admin_includes/book_time.php", 
    data:data, 
    success:function(html){ 
     // Use `that` instead of `this` in here. 
    } 
});//end ajax 

而且,我不知道是应该选择什么$(this, '.time_slot_holder'),但我不知道它会工作(需要看你的HTML标记)。

如果this'.time_slot_holder'的后裔,那么它会正常工作。

+1

上下文或内容? – 11684

+0

第二种选择正是需要的 - 谢谢:) – Sideshow

1

使用jQuery的元素作为背景

$('.time_slot_holder').click(function(){ 
    var data_day=$(this).data('agent_day'); 
    var data_time=$(this).data('agent_time'); 
    var data="agent_id="+agent_id+"&day="+data_day+"&time="+data_time 

    $.ajax({ 
     type:"POST", 
     url:"admin_includes/book_time.php", 
     data:data, 
     context : $(this), 
     success:function(html){ 
      var split_html=html.split("|") 
      if(split_html[0]=="B"){ 
       //booking exists 
       alert("Bookings for this time slot exist. Contact Agent to arrange a re-assignment of this appointmnet."); 

      } 
      if(split_html[0]=="C"){ 
       //added to db 
       $(this).css('background-color', 'red'); 
      } 
      if(split_html[0]=="D"){ 

      } 


     } 
    });//end ajax 

}); 
[jQuery的AJAX调用:$(本)成功后不能正常工作]的
相关问题