class Mess {
MessyMethod() {
startSession = function () {
document.querySelector('.rds-form').addEventListener('submit', function(e) {
e.preventDefault();
alert('form submitted');
});
}
}
}
<form class="rds-form">
<input /><button id="continueButton" type="submit">Submit</button>
</form>
伙计们,我有一个项目,其JavaScript逻辑如下:
export class Mess {
constructor(title, username) {
this.title = title;
this.username = username;
this.container = document.getElementById('originalContainer');
}
MessyMethod() {
this.startSession = function () {
var self = this;
let pwForm = pwAuthForm();
let div = document.createElement('div');
document.templates = [];
div.innerHTML = pwForm;
this.container.appendChild(div);
document.querySelector('.rds-form').addEventListener('submit', function(e) {
e.preventDefault();
alert('form submitted!');
});
}
}
}
index.html是:
<form class="rds-form">
<input /><button id="continueButton" type="submit">Submit</button>
</form>
因此,除非我将其document.querySelector()
从this.startSession
里面的里面拉出来,否则上述内容就无法成功提交MessyMethod
。我被问到在哪里startSession
被调用,好吧,它在任何地方都没有被调用。它在工作之前document.querySelector("continueButton").addEventListener("click", function ())
但是我的理解是,这是一个不好的表单,它应该以表单的类为目标并侦听提交,否则用户可以单击页面中的任意位置,然后表单将提交。我在这里走错了路吗?
您的代码正在运行
您的问题是如何称呼 startSession
这是工作示例(相同的代码):
class Mess {
constructor(title, username) {
this.title = title;
this.username = username;
this.container = document.getElementById('originalContainer');
}
MessyMethod() {
this.startSession = function () {
var self = this;
document.querySelector('.rds-form').addEventListener('submit', function(e) {
e.preventDefault();
alert('form submitted!');
});
//let pwForm = pwAuthForm();
//let div = document.createElement('div');
//document.templates = [];
//div.innerHTML = pwForm;
//this.container.appendChild(div);
}
}
}
// I added these 3 lines
var mess = new Mess("title !","user name !")
mess.MessyMethod()
mess.startSession()
<html>
<body>
<form class="rds-form">
<input /><button type="submit">Submit</button>
</form>
</body>
</html>
如果您想保留相同的代码骨架(我建议重构)
请注意,startSession
仅在运行时才构建该方法MessyMethod
因此,您需要先调用MessyMethod
然后再调用startSession
以实际添加提交事件侦听器
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句