简体   繁体   中英

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

My current problem is that I want to change the href of an tag before the page loads what it was previously pointing to.

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

I've tried something like this and it didn't work. I've tried:

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

in another file:

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

and this doesn't work, unless you put an alert before the change occurs, and then it does occur as expected. Any help would be greatly appreciated, it's my first time posting so apologies if the format isn't correct

you can do like this:

HTML:

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

EIDT:

The previous solution will create a recursive loop of event, do like this instead

JQUERY:

$(function () {

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

    e.preventDefault(); //stop default behaviour

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

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

});

or:

$(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

    }
  });

});

UPDATED:

$(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;

        }
      });

    });

You can redirect a link via JS by something like this

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

You can do by HTML

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

JQuery

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

Your first method was correct. It seems that you've just forgotten to quote the text:

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

Don't change the href when the link before the click is processed. Instead, change it earlier , either on page load and/or (if the link opens a new window or otherwise doesn't cause a window reload) after it's clicked.

Example: Live Copy

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));
}

Note how the link always takes the user to where they can see in advance it's taking them, then updates as appropriate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM