[英]Explain why function won't execute when button clicked
我无法让 signIn 函数中的按钮在 onclick 事件上执行。 我需要帮助了解我做错了什么以及需要做些什么来解决它。 我正在构建一个简单的愚蠢应用程序来学习 javascript/typescript。 应用程序中早期的其他按钮工作,我能够转换 DOM,但登录函数中内置的按钮似乎没有触发并执行 isValid 函数。 我在网络控制台中没有错误。 我完全不明白为什么按钮不会执行 isValid 函数。
var App = /** @class */ (function () { function App() { this.init(); } App.prototype.init = function () { if (!window['WebSocket']) { console.log("BROWSER NOT SUPPORTED"); document.body.innerHTML = "BROWSER NOT SUPPORTED"; } document.documentElement.style.background = "green"; document.title = "App"; var sin = document.createElement("button"); sin.id = "sin"; sin.innerHTML = "SIGN IN"; sin.onclick = this.signIn; var sup = document.createElement("button"); sup.id = "signup"; sup.innerHTML = "SIGN UP"; sup.onclick = this.signUp; var landing = document.createElement("div"); landing.id = "landing"; landing.style.position = "absolute"; landing.style.left = "50%"; landing.style.top = "50%"; landing.style.transform = "translate(-50%,-50%)"; landing.appendChild(sin); landing.appendChild(sup); document.body.appendChild(landing); }; App.prototype.signIn = function () { document.body.removeChild(document.getElementById("landing")); var user = document.createElement("input"); user.type = "text"; user.id = "username"; user.placeholder = " username"; user.style.border = "1px solid"; user.style.width = "150px"; var pass = document.createElement("input"); pass.type = "password"; pass.id = "password"; pass.placeholder = " password"; pass.style.border = "1px solid"; pass.style.width = "150px"; var okay = document.createElement("button"); okay.innerHTML = "Sign in"; //I can't get the isValid function to execute. okay.onclick = this.isValid; var signin = document.createElement("div"); signin.id = "signin"; signin.style.position = "absolute"; signin.style.left = "50%"; signin.style.top = "50%"; signin.style.transform = "translate(-50%,-50%)"; signin.appendChild(user); signin.appendChild(document.createElement("br")); signin.appendChild(pass); signin.appendChild(document.createElement("br")); signin.appendChild(okay); document.body.appendChild(signin); }; App.prototype.signUp = function () { alert("alert!"); }; App.prototype.isValid = function () { alert("alert!"); }; return App; }()); window.onload = function () { var app = new App(); };
这是一个经典的范围界定问题。
添加okay
按钮后, this
不是指向您认为它指向的位置。
您认为this
指的是App
函数。 但是okay
按钮不是App
函数创建的,是sin
按钮创建的。 这就是为什么this
,在该位置,指向sin
按钮,因为没有isValid
在功能sin
按钮,你没有得到警告你想要的。
要解决此问题,您可以将this.isValid
更改为App.prototype.isValid
。
// from this
okay.onclick = this.isValid;
// to this
okay.onclick = App.prototype.isValid;
这将获得所需的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.