【问题标题】:Selecting an element within a JQuery function [duplicate]在JQuery函数中选择一个元素[重复]
【发布时间】:2013-07-08 14:24:54
【问题描述】:

我正在使用 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) 因为它超出了函数的范围。我能做什么?

谢谢!

【问题讨论】:

    标签: javascript jquery ajax


    【解决方案1】:

    最简单的方法是在 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
            }); 
    

    【讨论】:

      【解决方案2】:

      您可以简单地将$(this) 存储在一个变量中:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-11-09
        • 1970-01-01
        • 1970-01-01
        • 2013-03-03
        • 1970-01-01
        • 1970-01-01
        • 2015-01-17
        • 1970-01-01
        相关资源
        最近更新 更多