简体   繁体   中英

Why doesn't JavaScript event.preventDefault() work?

I have a JavaScript function for an anchor tag that has preventDefault() in it. However, it seems like the function only delays the default rather than prevent it.

The purpose of this function is to use Ajax to navigate within the website so that the page does not refresh when I click on an internal link.

This appears to work as intended when the site has no CSS, but when I add the CSS, this is what happens when I click on an internal link to go from Page A to Page B:

  1. Page B is properly loaded with all the HTML and CSS contents and the URL also changes via the Ajax method.
  2. The page then refreshes to show only the HTML contents that was previously there but without the CSS styling.
  3. The CSS styling finally appears.

I think this might be because preventDefault() only delayed the action of the "a" tag rather than completely disable it.

Is there any way to fix it?

Below is the code:

 const navigatePage = () => { event.preventDefault(); const a = new XMLHttpRequest(); const b = event.target.pathname; a.open('GET', b, true); a.onprogress = () => document.getElementsByTagName('body')[0].innerHTML = "Loading.."; a.onload = () => { if (a.status == 200) { window.location.pathname = b; document.getElementsByTagName('title')[0].textContent = new DOMParser().parseFromString(a.responseText, "text/html").head.childNodes[7].innerHTML; document.getElementsByTagName('body')[0].innerHTML = new DOMParser().parseFromString(a.responseText, "text/html").body.innerHTML; } } a.onerror = () => console.log('Error occured;'). a;send(); }
 :root { --main-color:red; --secondary-color:pink; --dark-color:#444; --light-color:#fafafa; --max-width:1000px; } *{margin:0;padding:0;box-sizing:border-box;text-decoration:none;color:var(--dark-color);} body { font-family: 'Montserrat', sans-serif; background-color:var(--light-color); color:var(--dark-color); display: grid; place-items: center; font-size: 20px; } header{width:100%;display:flex;flex-wrap: wrap;align-items: center;justify-content:space-between;} header img {height: 70px; width: 270px;}.max-width{width: clamp(0px,var(--max-width),90%);}
 <div class="max-width"> <header> <div><a href='/'><img src='logo-title.svg' alt="logo" /></a></div> <nav> <a href='/' onclick="navigatePage()">Home</a> <a href='about' onclick="navigatePage()">About</a> <a href='contact' onclick="navigatePage()">Contact</a> </nav> </header> <h1>Home Page</h1> <p>There are 2 other pages with a different lorem ipsums and with h1 tags that say "About Page" and "Contact Page" respectively</p> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam commodo rhoncus odio, nec interdum metus dignissim non. Nullam vel felis vel dolor finibus venenatis ac non quam. Donec sagittis sed libero vel aliquet. Ut finibus leo neque, quis consequat elit dictum at. Donec finibus tincidunt mauris ut ullamcorper. Sed bibendum viverra ante, eget pretium lectus porta sit amet. Mauris eget maximus nulla, at tempus odio. Nullam efficitur odio diam, et finibus sapien congue eu. Aenean luctus aliquet bibendum. Etiam erat erat, tincidunt feugiat felis at, mollis varius justo. Aenean dolor nisi, consequat vitae lacinia et, ullamcorper quis felis. Donec suscipit magna id urna interdum, ac pharetra arcu iaculis. Nulla et tristique neque, in auctor ipsum. Sed egestas, diam at ultricies blandit, enim nisl volutpat urna, eu dapibus elit massa ut nulla.</p> </div>

Try passing 'event' as an argument

const navigatePage = (event) => {
  event.preventDefault();
  // ... your code
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM