选择JQuery函数中的元素

use*_*500 1 javascript ajax jquery

我正在使用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; 

    });
Run Code Online (Sandbox Code Playgroud)

我试过用:

$(this).parent().append(html);
Run Code Online (Sandbox Code Playgroud)

但我认为问题是我不能使用$(this)因为它超出了函数的范围.我能做什么?

谢谢!

PSL*_*PSL 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; 

});
Run Code Online (Sandbox Code Playgroud)

或者使用contextajax的属性.

 $.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.
            }
        }); 
Run Code Online (Sandbox Code Playgroud)

或者您也可以使用$ .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
        }); 
Run Code Online (Sandbox Code Playgroud)

或使用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
        }); 
Run Code Online (Sandbox Code Playgroud)