我正在尝试使用 html、css 和 vanilla JS 制作 SPA(我对 JS 知之甚少)。我遇到的问题是,我正在使用的方法在我的标题中可以正常工作,其中我只有“a”,里面有文本。但是当我想使用 img 作为“a”时,脚本在 img 内部不起作用,它只允许我在 img 周围单击而不是在其内部单击。 我很感激任何帮助。 这是我的脚本和我遇到问题的部分的 html。
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",
"/vehicles": "./pages/vehicles.html",
"/services": "./pages/services.html",
"/contact": "./pages/contact.html",
"/financing": "./pages/financing.html",
"/locations": "./pages/locations.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();
<a href="/financing" onclick="route()" class="mainServices-section">
<div class="main-title">
<h2>Financing</h2>
</div>
<img src="../image/financing-image-colored.svg" alt="">
</a>
最佳答案
问题是当您单击<img>
时target
未设置为您的<a>
标记为event.target.href
是 undefined
.
而不是使用 onclick
属性,使用委托(delegate)事件监听器并检查它是否源自 <a>
标签或后代。
document.addEventListener("click", (e) => {
const anchor = e.target.closest("a[href]");
if (anchor) {
e.preventDefault();
window.history.pushState({}, "", anchor.href);
handleLocation();
}
});
关于javascript - 在 img 中运行脚本时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74649329/