![](/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.