单击元素时将jQuery选择器应用于表

时间:2012-07-03 15:00:16

标签: jquery ajax function scope this

我认为当需要根据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的回调。

2 个答案:

答案 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

});