我有一条路线
"/login"
,其中有 2 个输入字段 email
和 password
,并且在填写字段后还有一个可以单击的按钮,但是,如果有一个字段,我必须为这些字段添加一个事件侦听器Enter Keypress
因为我希望用户通过按回车键来发送数据,而不是通过鼠标手动单击按钮,并且我不想使用forms
。
现在,当我在主页中添加该事件侦听器(如下所示)时,它会显示
element is null
,因为它看不到它,因为它仍然没有将 "/login"
的内容加载到主页。
有什么方法可以以不同的方式访问这些元素
routes
?
这是索引页
"/"
的代码:
<!DOCTYPE html>
<html>
<head>
<title>Vanilla SPA Router</title>
<meta charset="UTF-8" />
<link rel="stylesheet" href="css/styles.css" />
<link href="https://cdn.jsdelivr.net/npm/@mdi/[email protected]/css/materialdesignicons.min.css" rel="stylesheet" />
</head>
<body>
<div id="root">
<nav id="main-nav" class="sidebar">
<a href="/" onclick="route()">Home</a>
<a href="/about" onclick="route()">About</a>
<a href="/lorem" onclick="route()">Lorem</a>
<a href="/login" onclick="route()">login</a>
</nav>
<div id="main-page"></div>
</div>
<script>
// adding event listener here for id elements password
var input = document.getElementById("password");
input.addEventListener("keypress", function(event) {
if (event.key === "Enter") {
event.preventDefault();
document.getElementById("login_btn").click();
}
});
// the login() will be called by login_btn, but I didn't include
// it for this question since it's unnecessary
</script>
<script src="router.js"></script>
</body>
登录页面的代码
"/login"
:
<input type="email" id="email" placeholder="email" />
<input type="password" placeholder="password" id="password" />
<button onClick="login()" id="login_btn" className="btn btn-primary">Login</button>
Javascript路由代码:
const route = (event) => {
event = event || window.event;
event.preventDefault();
window.history.pushState({}, "", event.target.href);
handleLocation();
};
const routes = {
404: "/pages/404.html",
"/": "/pages/index.html",
"/about": "/pages/about.html",
"/lorem": "/pages/lorem.html",
"/login": "/pages/login.html",
};
const handleLocation = async () => {
const path = window.location.pathname;
const route = routes[path] || routes[404];
const html = await fetch(route).then((data) => data.text());
document.getElementById("main-page").innerHTML = html;
};
window.onpopstate = handleLocation;
window.route = route;
handleLocation();
在
keypress
上收听 document
- 然后检查目标元素的 ID
document.addEventListener("keypress", function(event) {
if (event.target?.id === 'password') {
if (event.key === "Enter") {
event.preventDefault();
document.getElementById("login_btn").click();
}
}
});