簡體   English   中英

更改href后鏈接的Onclick不起作用,但在新標簽頁中打開有效

[英]Onclick of link does not work after changing href, but open in new tab works

我有下面的錨標簽。 我正在嘗試搜索具有值 xyz 的屬性,然后更改其 herf 並刪除不需要的屬性。

在控制台上執行此操作后,我可以看到 href 已更改,但單擊鏈接不起作用。 但是,當我在新選項卡中打開時,它會以新的 href 打開

<a data-data="test" data-name="xyz" href="#" class="button">this is a link</a>

var pmLink = document.querySelectorAll("[data-name='xyz']");

if (pmLink) {
    pmLink[0].href = "http://www.google.com";
    pmLink[0].removeAttribute("data-data");
    pmLink[0].removeAttribute("data-name");
    } 

更改為: var pmLink = document.querySelector("[data-name='xyz']");

工作片段:

 var pmLink = document.querySelector("[data-name='xyz']"); if (pmLink) { pmLink.setAttribute('href', 'http://www.google.com'); pmLink.removeAttribute("data-data"); pmLink.removeAttribute("data-name"); }
 <a data-data="test" data-name="xyz" href="#" class="button">this is a link</a>

如果您有多個data-name="xyz"則使用querySelectorAll然后您需要迭代和“ this ”。

希望有幫助! 享受代碼!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM