4 回答

TA贡献1770条经验 获得超3个赞
您可以获取链接并在点击后更改她
document.querySelector('span.arb').addEventListener('click', toogle)
function toogle(){
if( document.querySelector('span.arb').href === "domain.com"){
document.querySelector('span.arb').href = "domain.com/link"
} else if (document.querySelector('span.arb').href === "domain.com/link"){
document.querySelector('span.arb').href = "domain.com"
}

TA贡献1810条经验 获得超4个赞
将链接保存在数据属性中并使用它进行切换。
document.querySelector("[data-toggleHref]").addEventListener("click", function(){
//Get the link element
var a = document.querySelector("a");
var current = a;
//Log to demontrate only
console.log(this.dataset.togglehref);
//Update the link
a.href = this.dataset.togglehref;
//Set the data attribute for toggle
this.dataset.togglehref = current;
});
<a href="/pagea.html" id="target">Link</a>
<span data-toggleHref="/pageb.html">Click Me</span>

TA贡献1788条经验 获得超4个赞
尝试这个:
let count = 0;
document.querySelector('span.arb').addEventListener('click', function () {
count++;
document.querySelector('a').href = "http://example.com";
if (count == 1) {
document.querySelector('a').href = "http://example.com/ar";
} else {
document.querySelector('a').href = "http://example.com";
}
});
<a href="http://example.com">Link</a>
<span class="arb">Click Me</span>

TA贡献1719条经验 获得超6个赞
试试这个代码:
document.querySelector('span.arb').addEventListener('click', function() {
if(a.href == "example.com") {
a.href="example.com/ar";
} else {
a.href="example.com";
}
})
或更短的答案使用三元运算符:
document.querySelector('span.arb').addEventListener('click', function() {
a.href = a.href == "example.com" ? "example.com/ar" : "example.com";
})
添加回答
举报