繁体   English   中英

如果 href 属性不是您想要的,如何制作重定向链接

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

我试过了,但没用,因为我在 javascript 的能力几乎为零

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));
}

我希望如果#change 不存在,那么页面将重定向,但如果存在但 href 属性不是您想要的,那么页面也会重定向。 这是我的 html 代码

<!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>

尝试这个:

<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>

我没有清楚地了解您的目标,但据我所知

  • 如果没有带有#change id 的元素,您想重定向页面,页面应该重定向。
  • 如果元素存在但链接与我们想要的不同,则重定向到特定位置。 我对吗。

我假设您要重定向到https://google.com

首先,你要防止使用js重定向链接,有两种方法

  1. <a id="logout-link" href="javascript:void(0);">Logout</a>但这对你不起作用,因为你想在href中有一个链接。
  2. 您必须使用event.preventDefault(); 功能。

然后你的代码应该看起来像

 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 使用了一些 function 一个typeof用于获取变量的类型。 它的值可以是Stringnumber等......,

我希望这会帮助你

快乐编码:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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