Using jQuery to programmatically click an link

后端 未结 9 1896
一生所求
一生所求 2020-11-29 03:55

I know this question has been asked before, but after a search on the web I can\'t seem to find a straight forward answer.

the HTML

         


        
相关标签:
9条回答
  • 2020-11-29 04:30

    If you are using jQuery, you can do it with jQuery.trigger http://api.jquery.com/trigger/

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
    </head>
    <body>
        <a id="foo" onclick="action()"></a>
        <script type="text/javascript">
            function action(){
                window.location.replace("http://stackoverflow.com/q/9081426/5526354")
            }
    
            $("#foo").trigger("click");
        </script>
    </body>
    </html>
    
    0 讨论(0)
  • 2020-11-29 04:33

    Add onclick="window.location = this.href" to your <a> element. After this modification it could be .click()ed with expected behaviour. To do so with every link on your page, you can add this:

    <script type="text/javascript">
        $(function () {
            $("a").attr("onclick", "window.location = this.href");
        });
    </script>
    
    0 讨论(0)
  • 2020-11-29 04:34

    I had similar issue. try this $('#myAnchor').get(0).click();this works for me

    0 讨论(0)
提交回复
热议问题