简体   繁体   中英

How to emulate click on anchor tag with javascript?

On my site, I have a div container, which contains a <input> , and a <a onclick="DoSomeStuff();" href="#" target="_blank"> <a onclick="DoSomeStuff();" href="#" target="_blank"> element, which acts as a button. Now, DoSomeStuff(); modifies the href attribute based on the value of the input element.

I need to emulate click on this anchor tag after user pressed enter on an input element. I know how to detect this enter, but I don't know how to click this anchor. jQuery's .click() is not working in here, it only fires onclick() of the anchor tag, but does not actually click the anchor.

Edit : Here is an example on what I want to do: http://jsfiddle.net/JZYWZ/ . It triggers the onclick event of the anchor tag, but does not follow the link in new tab.

Browsers are very strict about opening links in new tabs/windows through javascript.

If they allowed you to have javascript click and open a new tab when the user presses enter (for what you know to be legitimate reasons), that feature could be abused by spammers to have javascript click ads and spam links when the user does anything . Sadly there's no way the browser can tell your linked page is legitimate and not spam or monetised clickbait.

Pretty much the only option to open the url in new tab using javascript is window.open which you've already tried: the browser will always look to the user's settings on popup blocking and on whether to open in tabs or windows - and the default settings are strict, particularly in Firefox and Internet Explorer (less so in Chrome and Safari).


A possible alternate approach where you won't be fighting the browser's anti-spam defences is to open the content in a modal overlay (iframe-based if you need multiple pages). Here's one example library .

It'll be similar from a UI point of view - giving the user related content in a form where they can just close it and return to the main page when they're done with it.

Modal overlays are widely used and likely to be familiar with users. For example, they're now pretty standard for sharing pages, logins and other pieces of simple interaction or side content. Example :

在此输入图像描述

EDIT

After some additional testing....

$('input[type="text"]').on('keyup', function(event){
    if(event.keyCode === 13){
        DoSomeStuff();
        window.open($('a').attr('href'));      
    }
});

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