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