我认为当需要根据Ajax返回对元素进行简单的css更改时,我遇到了'this'范围的问题。
$('.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请求的笨拙的拆分回调,这只是尝试通过数据属性识别元素。基本上我需要将被点击的元素的引用引用到ajax的回调。
答案 0 :(得分: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 :(得分: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
});