javascript - 将上下文 "this"从一个函数传递到另一个函数中?

标签 javascript jquery html

我正在用表单练习 ajax,并且..我想为了学习而越来越迷惑自己。

这可能没有任何意义,但我正在尝试记录名字和姓氏,特别是通过 conLog 函数。但它显示为未定义,因为我认为上下文“this”不存在,并且我不确定如何设置它。不过,我设法将其设置在 ajax 内。

因此,如果您打开日志,第二行显示未定义,而在第一行中,将记录第一个表单的输入。

https://jsfiddle.net/2oLjqv7c/3/

假设这就是问题所在,我如何将“this”传递到 conLog 中?

提前致谢!我发现了一些有同样问题的帖子,但是叹息......我想我无法理解它,除非它应用于我的个人问题(我猜仍然需要学习阅读其他人的代码)。

HTML

<form action="/echo/html/" id="form1" method="post">
  First Name:
  <input type="text" value="first" id="firstName">
  <br/>
  Last Name:
  <input type="text" value="last" id="lastName">
  <br/>
  <button type="submit" form="form1" value="submit">Submit</button>
</form>

Javascript/jQuery

function Display(el) {
    this.el = el;
  this.firstName = this.el.find("#firstName");
  this.lastName = this.el.find("#lastName");
  var confirmation = this;
    this.el.on('submit', function(e) {
        e.preventDefault();
    $.ajax('/echo/html/', {
        success: function() {
        console.log('success' + " " + this.firstName.val());
        this.conLog(this.firstName.val(), this.lastName.val());
      },
      error: function() {
        console.log('fail');
      },
      timeout: 3000,
      context: confirmation
    });
  });

  this.conLog = function(first, last) {
    this.first = this.first;
    this.last = this.last;
    console.log(this.first + " " + this.last);
  };
}

$(document).ready(function() {
    Display($('#form1'));
})

最佳答案

您不需要传递this。因为您已经传递了 firstlast 参数。只需像这样直接使用它们即可:

this.conLog = function(first, last) {
  console.log(first + " " + last);
};

请注意,我将 this.firstthis.last 更改为 firstlast

关于javascript - 将上下文 "this"从一个函数传递到另一个函数中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37267475/

相关文章:

javascript - 当我使用参数触发自定义事件时,事件处理程序的参数未定义

javascript - jquery div onclick调用函数

javascript - 如何在 jQuery 中访问名称中包含数组的单选按钮?

javascript - 使用 jquery 启用禁用动态元素

html - Bootstrap 如何让文本无响应但在 div 内?

javascript - React + Redux HOC 加载器

Angular 6 with bootstrap 4 - 表单验证电子邮件

javascript - Codeigniter AJAX 通过 POST 将数组传递到另一个页面

javascript - 在div上使用鼠标滚动来触发动画?

javascript - Ajax 正在生成所需的代码(Fusion Chart),但 div 未更新