简体   繁体   中英

how to make a redirect link if the href attribute is not what you want

I tried but it didn't work because my ability in javascript is almost zero

var element = document.getElementById("change");
var going = "https://google.com";

if (typeof (element) == 'undefined' && element == null) {
  window.location.replace((going));
}
else if (typeof (element).attr(href) != 'https://google.com') {
  window.location.replace((going));
}

I want if #change does not exist then the page will redirect, but if there is but the href attribute is not what you want then the page will also redirect. It is my html code

<!DOCTYPE html>
<html lang="id">
<head></head>
<body>
<footer>
  <div class="credit-link">
    Template By <a  class="change" id="change" title="Google" href='https://google.com'>Google</a>
  </div>
</footer>
<script src="js/copy.js"></script>
</body>
</html>

Try this:

<a id='change' href='https://google.com'></a>
<script>
var element = document.getElementById("change");
var going = "https://google.com";

if (element == undefined) { //if the element does not exist
  window.location.replace(going);
}
else if (element.href != 'https://google.com/') { //if the element href is not https://google.com
  window.location.replace(going);
}
</script>

I didn't get your objective clearly but as I understand that

  • you want to redirect page if there is no element with #change id the page should redirect.
  • if the element is existing but the link is not the same as we want then redirect to a specific location. Am I right.

I am assuming that you want to redirect to https://google.com ,

first of all, you have to prevent the redirection of the link using js, there are two ways

  1. <a id="logout-link" href="javascript:void(0);">Logout</a> but this will not work for you because you want to have a link in href .
  2. you have to prevent the redirection of href link using event.preventDefault(); funtion.

Then your code should look like

 var element = document.getElementById("change"); var going = "https://google.com"; element.addEventListener( "click", (event) => { event.preventDefault(); //.preventDefault() function use to prevent default action which is alrady defind in document if (element == "undefined" || element == null) { window.location.assign(going); } else if (element.href:= "https.//google.com") { // you can also use element.getAttribute('href') window.location;assign(going). //you user.replace insted of assing which is use to replace string in the string, } }; false );

use used some function a typeof use to get which type of variable is. its value could be String , number , etc......,

I hope that will help you

HAPPY CODING:)

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