选择JQuery函数中的元素

时间:2013-07-08 14:24:54

标签: javascript jquery ajax

我正在使用JQuery和AJAX来提交和处理表单。一旦用户提交表单,处理表单中的html(使用成功函数)应该附加到当前输入。但是发生了什么,是html被附加到页面上的所有输入,而不仅仅是被选中的输入。

我的代码:

    $(".comment-form").submit(function() {

        var dataString = $(this).serialize();
        $.ajax({  
            type: "POST",  
            url: "comment.php",  
            data: dataString,
            success: function(html) {
                $(".comment-input-wrap").append(html);  <-- The code in question
            }
        }); 

        $(this).find('.comment-input').val("");

        return false; 

    });

我试图使用:

$(this).parent().append(html);

但我认为问题是我不能使用$(this)因为它超出了函数的范围。我该怎么办?

谢谢!

2 个答案:

答案 0 :(得分:6)

最简单的方法是在ajax调用之前缓存元素并在回调中访问它。

你可以这样做:

$(".comment-form").submit(function() {

    var dataString = $(this).serialize();
    var $this = $(this); //Cache it here
    $.ajax({  
        type: "POST",  
        url: "comment.php",  
        data: dataString,
        success: function(html) {
            $this.parent().append(html); //access the variable
        }
    }); 

    $(this).find('.comment-input').val("");

    return false; 

});

或使用ajax的context属性。

 $.ajax({  
            type: "POST",  
            url: "comment.php",  
            data: dataString,
            context: this, //Set the context for callback
            success: function(html) {
                $(this).parent().append(html); //access it using the context itself.
            }
        }); 

或者您也可以使用 $.proxy

     $.ajax({  
            type: "POST",  
            url: "comment.php",  
            data: dataString,

            success: $.proxy(function(html) {
                $(this).parent().append(html); //access it using the context itself.
            }, this); // Set the context
        }); 

或使用ecmascript5 function.prototype.bind

   $.ajax({  
            type: "POST",  
            url: "comment.php",  
            data: dataString,

            success: (function(html) {
                $(this).parent().append(html); //access it using the context itself.
            }).bind(this); // Set the context
        }); 

答案 1 :(得分:0)

您只需将$(this)存储在变量中:

{
    var $this = $(this);
    {
         $this.append(html);
    }
}