[英]How can I achieve click event in JavaScript?
我在頁面上選擇了一個 span 元素。 對於第一次點擊,我希望它鏈接到另一個頁面。 在第二次單擊時,我希望它返回到原始頁面。
例如,我有一個與example.com
的鏈接,這是原始鏈接。 當這個元素“abcd”被點擊時,我希望它鏈接到example.com/ar
,當它再次點擊時我希望它返回到example.com
。
document.querySelector('span.arb').addEventListener('click', function() {
a.href="example.com";
})
如何使用上述方法完成此操作?
嘗試這個:
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>
你可以得到鏈接並在點擊后改變她
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"
}
將鏈接保存在數據屬性中並使用它進行切換。
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>
試試這個代碼:
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";
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.