简体   繁体   中英

JavaScript keeps reloading my page

I am running this script on my page to replace mc= to MediaCode= in my url, the script works but it keeps reloading the page over and over.

This is the script:

<script>location.href = location.href.replace('mc=', 'MediaCode=')</script>

when you put

location.href = someHref

you make js to reload the page. Then, I gues, it meets that line again and continues reloading

Why not put this line into an if condition? This will check whether the URL contains the desired string or not and reload based on that:

const mcQueryParam = /mc\=/;

if(location.href.match(mcQueryParam)){
  location.href = location.href.replace(mcQueryParam, "MediaCode=");
}

The solution to this is a slight alteration to Xufox's solution

    <script type="text/javascript">$(document).ready(function () {
if(window.location.href.indexOf("mc=") > -1) {
location.href = location.href.replace('mc=', 'MediaCode=')
}});

Many thanks to Xufox

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