2013-07-08 2 views
1

Я использую JQuery и AJAX для отправки и обработки формы. Когда пользователь отправляет форму, html из формы обработки (используя функцию успеха) должен быть добавлен к текущему вводу. Но что происходит, это то, что html добавляется ко всем входам на странице, а не только к выбранному.Выбор элемента в функции JQuery

Мой код:

$(".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); 

Но я думаю, что проблема в том, что я не могу использовать $ (это), поскольку она выходит за рамки из функция. Что я могу сделать?

Спасибо!

ответ

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; 

}); 

Или использовать context свойство Ajax.

$.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 
     }); 
0

Вы можете просто хранить $(this) в переменной:

{ 
    var $this = $(this); 
    { 
     $this.append(html); 
    } 
} 
Смежные вопросы