问题描述
你能告诉我如何修改这个 javascript 代码吗?我想在加载第二个页面 (capture.html) 时执行它,而不是在加载第一个页面 (index.html) 时执行它:
window.addEventListener('/load',myFunction);
它在 index.html 页面中工作正常,但我在 capture.html 页面中也需要它。我试过了:
window.addEventListener('/capture/load',myFunction);
但它不起作用。
解决方法
您无法指定要附加事件的路由(至少不是像您尝试那样在 addEventListener()
API 内)。没有“/load”或“/capture/load”事件。但是您可以在处理程序中定义取决于当前路由的逻辑,如下所示:
const handler = () => {
const {pathname} = window.location;
if (/\/?capture(\.html?)?$/.test(pathname)) {
// ADD YOUR CODE HERE
}
};
window.addEventListener('load',handler);
如果需要,您甚至可以在附加事件侦听器之前执行相同的检查。