无法使用 onclick 函数访问之前在 class 上设置的变量
Cannot access previously set variable on class with onclick function
所以我试图通过使用 类 和一个 init 函数来组织我的 javascript 项目,现在我遇到了这个以前从未遇到过的奇怪问题。这是我的代码:
class App {
constructor() {
this._username;
}
authenticate() {
this._username = "test";
}
submitForm() {
console.log(this._username);
}
}
const init = function () {
const app = new App();
document.getElementById("authenticationVerify").onclick = app.authenticate;
document.getElementById("btnSendSMS").onclick = app.submitForm;
}
window.onload = init;
和HTML(简体)
<body>
<main>
<form id="formSendSMS">
<input type="button" name="send" id="btnSendSMS" value="Versturen">
</form>
<div id="authentication-prompt">
<form>
<input type="button" name="login" id="authenticationVerify" value="Log in" class="button blue">
</form>
</div>
</main>
<script src="js/mainBack.js" type="text/javascript"></script>
</body>
</html>
正如您在控制台中看到的那样,当我激活第二次按下按钮时我得到“未定义”,但我真的不知道为什么会这样,因为 'app' 没有被重新声明。
亲切的问候,
碧玉
这不是捕获 点击事件 的正确方法。
从你的js代码,我已经成功地做了一个工作示例。
另外,JS函数不带括号是不能调用的。
.
给出了一个很好的例子
class App {
constructor() {
this._username;
}
authenticate() {
this._username = "test";
}
submitForm() {
console.log(this._username);
}
}
const init = function () {
const app = new App();
document.getElementById("authenticationVerify").onclick = function(e){app.authenticate()};
document.getElementById("btnSendSMS").onclick = function(e){app.submitForm()};
}
window.onload = init;
<button id="authenticationVerify">AUTH</button>
<button id="btnSendSMS">SMS</button>
所以我试图通过使用 类 和一个 init 函数来组织我的 javascript 项目,现在我遇到了这个以前从未遇到过的奇怪问题。这是我的代码:
class App {
constructor() {
this._username;
}
authenticate() {
this._username = "test";
}
submitForm() {
console.log(this._username);
}
}
const init = function () {
const app = new App();
document.getElementById("authenticationVerify").onclick = app.authenticate;
document.getElementById("btnSendSMS").onclick = app.submitForm;
}
window.onload = init;
和HTML(简体)
<body>
<main>
<form id="formSendSMS">
<input type="button" name="send" id="btnSendSMS" value="Versturen">
</form>
<div id="authentication-prompt">
<form>
<input type="button" name="login" id="authenticationVerify" value="Log in" class="button blue">
</form>
</div>
</main>
<script src="js/mainBack.js" type="text/javascript"></script>
</body>
</html>
正如您在控制台中看到的那样,当我激活第二次按下按钮时我得到“未定义”,但我真的不知道为什么会这样,因为 'app' 没有被重新声明。
亲切的问候, 碧玉
这不是捕获 点击事件 的正确方法。 从你的js代码,我已经成功地做了一个工作示例。
另外,JS函数不带括号是不能调用的。
class App {
constructor() {
this._username;
}
authenticate() {
this._username = "test";
}
submitForm() {
console.log(this._username);
}
}
const init = function () {
const app = new App();
document.getElementById("authenticationVerify").onclick = function(e){app.authenticate()};
document.getElementById("btnSendSMS").onclick = function(e){app.submitForm()};
}
window.onload = init;
<button id="authenticationVerify">AUTH</button>
<button id="btnSendSMS">SMS</button>