[英]JavaScript Mouse Click addEventListener Not Working
That addEventListener("click", forgotPassword)
is not working when // ADD PANEL TO BODY
event is calling. // ADD PANEL TO BODY
调用“将// ADD PANEL TO BODY
addEventListener("click", forgotPassword)
事件时addEventListener("click", forgotPassword)
不起作用。 Please Help to fix this. 请帮助解决此问题。
Javascript: Javascript:
var forgot_password_btn = document.querySelector("#forgot_password");
var theme_panel = "<div id=\"change-theme\"><a href=\"javascript:;\" class=\"dark\">DARK</a><a href=\"javascript:;\" class=\"light\">LIGHT</a></div>";
if (forgot_password_btn) {
forgot_password_btn.addEventListener("click", forgotPassword);
}
function forgotPassword() {
console.log("clicked");
}
// ADD PANEL TO BODY
window.onload = function () {
document.body.innerHTML += theme_panel;
};
HTML: HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<a href="#" id="forgot_password">Forgot</a>
</body>
</html>
The DOM is not ready when you are fetching the forgot_password element. 提取forgot_password元素时,DOM未准备好。 Therefore, no binding is made.
因此,不进行绑定。 Put the logic inside the onload event:
将逻辑放入onload事件中:
function forgotPassword() {
console.log("clicked");
}
// ADD PANEL TO BODY
window.onload = function () {
var forgot_password_btn = document.querySelector("#forgot_password");
var theme_panel = "<div id=\"change-theme\"><a href=\"javascript:;\" class=\"dark\">DARK</a><a href=\"javascript:;\" class=\"light\">LIGHT</a></div>";
if (forgot_password_btn) {
forgot_password_btn.addEventListener("click", forgotPassword);
}
};
Also, you should avoid inserting HTML content directly in the JS like that. 另外,您应该避免这样直接在JS中插入HTML内容。 Put it in the HTML or use templates.
将其放入HTML或使用模板。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.