我希望我的问题在某种程度上可以理解,我有一个 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/