簡體   English   中英

在<a>代碼觸發前</a>更改其href

[英]Changing the href of an <a> tag before it fires

我當前的問題是,我想在頁面加載之前指向的頁面之前更改標簽的href。

<a href = "#oldLink" onclick = "this.href = #newLink"></a>

我已經嘗試過類似的方法,但是沒有用。 我試過了:

<a href = "#oldLink" onclick = "changeLink();"></a>

在另一個文件中:

changeLink(){
    $("a").attr("href", "#newLink");
}

並且這是行不通的,除非您在更改發生之前發出警報,然后確實按預期發生。 任何幫助將不勝感激,這是我第一次發布,如果格式不正確,我們深表歉意

您可以這樣:

HTML:

<a href = "#oldLink" id="link"></a>

EIDT:

先前的解決方案將創建一個事件的遞歸循環,而不是這樣做

JQUERY:

$(function () {

$("#link").on("click", function (e) {

    e.preventDefault(); //stop default behaviour

    $(this).attr("href", "#newLink"); // change link href

    window.location.href = "#link2";
  });

});

要么:

$(function () {

$("#link").on("click", function (e) {

    if ($(this).attr('href') === '#oldLink') // check if it is old link
    {

        e.preventDefault(); //stop default behaviour

        $(this).attr("href", "#newLink"); // change link href

        $(this).trigger("click"); // click link programmatically

    }
  });

});

更新:

$(function () {

    $("#link").on("click", function (e) {

        if ($(this).attr('href') === '#oldLink') // check if it is old link
        {

            $(this).attr("href", "#newLink"); // change link href

            $(this).trigger("click"); // click link programmatically

            return false;

        }
      });

    });

您可以通過JS這樣重定向鏈接

changeLink(e){
    window.location = "#newLink";
    e.preventDefault();
}

您可以通過HTML來完成

<a href = "#oldLink">abc</a>

jQuery查詢

$('a').attr("href", "some url");

您的第一種方法是正確的。 似乎您只是忘了引用文本了:

<a href = "#oldLink" onclick = "this.href = '#newLink';"></a>

處理點擊之前的鏈接時,請勿更改href 取而代之的是, 單擊頁面加載和/或(如果鏈接打開一個新窗口,否則不會導致窗口重新加載) 之前 ,對其進行更早的更改。

示例: 實時復制

var link = $("#link");

setRandomLink();

link.click(function() {
  // Allow the link to be followed, then update it
  // with a new random value
  setTimeout(setRandomLink, 0);
});

function setRandomLink() {
  link.attr("href", "#" + Math.floor(Math.random() * 100));
}

請注意,鏈接如何始終將用戶帶到他們可以看到的預先位置,然后適當地進行更新。

暫無
暫無

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

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