Pergunta

I have a link in my page.

<a onclick="Click()">Click me</a>

When I click this link, fires onclick event that call Click function. In this function, I have some javascript code and then, I want to redirect to another page.

function Click() { 
    //some code
    window.location = url;
}

When user right click on link and select "Open in new tab", new tab opens, and url is: "about:blank".

How to I correct this? Thanks.

Foi útil?

Solução

The key is not to replace anchor functionality with Javascript. Anchors are designed to take you to a new URL. If you have an anchor, use it as an anchor (eg, set a href on it). Don't bind a click event that uses window.location to redirect to a new url.

Your current anchor has no href. So when you try and open it in a new tab, there's no surprise that nothing loads. You're literally opening nothing in the new tab.

If you really need to set the URL dynamically, then change the href of the element using javascript. For example:

document.getElementById('my-element').href = new_href;

It goes without saying that this needs to be done before the anchor is clicked (not on click). For example, on window.load, or the completion of the function that generates the dynamic URL.

Outras dicas

Use window.open function and pass _blank in second argument function

  function Click() { 
    //some code
    window.open(url,'_blank');
} 

you should correct your anchor tag to be something like this:

   <a href="http://yourLink.com" target="_blank" onclick="Click();">link text</a>

this way when user click on the link it'll open in new tab and you'll execute the Click function.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top