亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在JavaScript中實現點擊事件?

如何在JavaScript中實現點擊事件?

繁星點點滴滴 2023-07-14 09:38:40
我在頁面上選擇一個 span 元素。對于第一次點擊,我希望它鏈接到另一個頁面。第二次單擊時,我希望它返回到原始頁面。例如,我有一個 的鏈接example.com,這是原始的。當單擊此元素“abcd”時,我希望它鏈接到example.com/ar,當再次單擊它時,我希望它返回到example.com。document.querySelector('span.arb').addEventListener('click', function() {   a.href="example.com"; })我如何使用上述內容完成此操作?
查看完整描述

4 回答

?
德瑪西亞99

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"

}


查看完整回答
反對 回復 2023-07-14
?
蝴蝶不菲

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>


查看完整回答
反對 回復 2023-07-14
?
尚方寶劍之說

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>


查看完整回答
反對 回復 2023-07-14
?
慕俠2389804

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";

})


查看完整回答
反對 回復 2023-07-14
  • 4 回答
  • 0 關注
  • 182 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號