4 回答

TA貢獻(xiàn)1770條經(jīng)驗(yàn) 獲得超3個(gè)贊
您可以獲取鏈接并在點(diǎn)擊后更改她
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貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊
將鏈接保存在數(shù)據(jù)屬性中并使用它進(jìn)行切換。
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貢獻(xiàn)1788條經(jīng)驗(yàn) 獲得超4個(gè)贊
嘗試這個(gè):
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貢獻(xiàn)1719條經(jīng)驗(yàn) 獲得超6個(gè)贊
試試這個(gè)代碼:
document.querySelector('span.arb').addEventListener('click', function() {
if(a.href == "example.com") {
a.href="example.com/ar";
} else {
a.href="example.com";
}
})
或更短的答案使用三元運(yùn)算符:
document.querySelector('span.arb').addEventListener('click', function() {
a.href = a.href == "example.com" ? "example.com/ar" : "example.com";
})
添加回答
舉報(bào)