0

我有以下表格:

<form  class="friend_form" action="/friend"  data-id="<?php echo $i;?>">    
    <input type="submit"  value="no" name="hey"/>
</form>

以及以下脚本:

$('.friend_form').on('submit', function(){
    $.ajax({
       url: $(this).attr('action'), 
       type: $(this).attr('method'), 
       success: function(html)
       {
           console.log('foo'+$(this).attr('data-id'));
       }
    });
   return false;
});

我要做的是获取 data-id 属性值,但它返回未定义的值。

我的代码有什么问题?

4

2 回答 2

2

回调中的“this”不是您认为的那样:

$('.friend_form').on('submit', function(){
    var self = this;
    $.ajax({
       url: $(this).attr('action'), 
       type: $(this).attr('method'), 
       success: function(html)
       {
           console.log('foo'+$(self).attr('data-id'));
       }
    });
   return false;
});

或者使用闭包:

$('.friend_form').on('submit', function () {
    (function (self) {
        $.ajax({
            url: $(this).attr('action'),
            type: $(this).attr('method'),
            success: function (html) {
                console.log('foo' + $(self).attr('data-id'));
            }
        });
    })(this);
    return false;
});

或者使用 ajax 选项上下文:

$('.friend_form').on('submit', function(){
    $.ajax({
       url: $(this).attr('action'), 
       type: $(this).attr('method'),
       context: this, 
       success: function(html)
       {
           console.log('foo'+$(this).attr('data-id'));
       }
    });
   return false;
});
于 2013-06-04T19:07:30.880 回答
1

您需要将上下文传递给成功回调,或者只需在方法中设置一个变量。AJAX 回调中的 this 上下文包含 jqxhr 对象上下文,而不是元素的上下文。

$('.friend_form').on('submit', function(){
  var $this = $(this); //<-- Set up here.
    $.ajax({
       url: $(this).attr('action'), 
       type: $(this).attr('method'), 
       success: function(html)
       {
           console.log('foo'+ $this.attr('data-id')); // access it using $this
       }
    });
   return false;
});

你也可以使用 $.proxy 来传递上下文,但这里不是必须的,而是另一种选择。请注意,这会将回调中的上下文完全更改为 DOM 元素,因此是不需要的。

  $.ajax({
       url: $(this).attr('action'), 
       type: $(this).attr('method'), 
       success: $.proxy(function(html)
       {
           console.log('foo'+ $(this).attr('data-id')); // Now this here is the form element.
       }, this)
    });
于 2013-06-04T19:07:27.170 回答