![](/img/trans.png)
[英]Why would you want an anchor tag that is not a link? (no href attribute?)
[英]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重定向鏈接,有兩種方法
<a id="logout-link" href="javascript:void(0);">Logout</a>
但這對你不起作用,因為你想在href
中有一個鏈接。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
用於獲取變量的類型。 它的值可以是String
,number
等......,
我希望這會幫助你
快樂編碼:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.