javascript - 通过 JavaScript 类处理时,序列化时表单字段为空

标签 javascript jquery scope es6-modules es6-class

我希望我的问题在某种程度上可以理解,我有一个 ES6 类,它在常规表单上初始化,然后通过 ajax 调用进行处理(不包含在示例中)。

当我尝试序列化 formData 时,它返回空而不是first_name 输入的值。表单上的其他操作(例如添加或删除类等)工作正常,只是表单不会返回任何数据。我想我不知何故在范围内失去了我的 $.this 。我是新尝试在模块和类以及抽象编码中构建我的 JavaScript。当我使用常规 jQuery 就绪代码调用和处理它时,该表单按预期工作,但只是无法弄清楚问题出在哪里。

脚本.js

import $ from 'jquery'

class CustomSubmit extends window.HTMLElement {
  constructor (...args) {
    const self = super(...args)
    self.init()
    return self
  }

  init () {
    this.$ = $(this)
    this.resolveElements()
    this.bindFunctions()
    this.bindEvents()
  }

  resolveElements () {
    // Get the Form
    this.$bidForm = $( '#CustomSubmitForm' , this)
  }

  bindFunctions () {
      this.sendForm = this.sendForm.bind(this)
  }

  bindEvents () {
    // Attach sendForm function to Form Submit  
    this.$.submit('[data-form-submit]', this.sendForm)
  }

  sendForm (e) {

    e.preventDefault()
    const formData = this.$.serialize()
    // here is the problem, formData is empty
    console.log(formData)

  }
}

window.customElements.define('submit-form', CustomSubmit, { extends: 'form' })

表单.html

<form is="submit-form" id="CustomSubmitForm">
<input type="text" name="first_name" id="first_name">
<button type="submit" [data-form-submit] >Submit Form</button>
</form>

最佳答案

问题似乎在于您正在使用

class CustomSubmit extends window.HTMLElement {

不过是一个普通的HTMLElement没有any <form> -specific properties and methods这将允许 jQuery 从所有元素收集值。相反,使用

class CustomSubmit extends window.HTMLFormElement {
//                                    ^^^^

关于javascript - 通过 JavaScript 类处理时,序列化时表单字段为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61586998/

相关文章:

javascript - 将 javascript 变量传递给 ruby​​ on rails Controller 以进一步发送 api

javascript - 为什么 redux-saga 使用 put 方法而不是 dispatch?

javascript - 使用jQuery获取div.class的内容替换title标签的内容

javascript - 为什么 *this* 不是 *this*?

javascript - 请求 promise 总是返回响应而不是返回值

javascript - 帮助将 CSS 添加到 jquery

javascript - 苹果商店指南。混合移动应用程序中的外部 JavaScript 文件

javascript - 为 fadeToggle 添加关闭单击和转义功能

javascript - 这个 jQuery 示例有什么问题?

php - PHP foreach 循环中的数组范围