Simulating a click in jQuery/JavaScript on a link

后端 未结 7 1561
野趣味
野趣味 2020-12-01 04:45

I want to simulate a click on any link on a page using JavaScript. If that link has some function binded to its \'onclick\' event (by any other JS I don\'t have any control

7条回答
  •  南方客
    南方客 (楼主)
    2020-12-01 05:27

    You can use the the click function to trigger the click event on the selected element.

    Example:

    $( 'selector for your link' ).click ();
    

    You can learn about various selectors in jQuery's documentation.

    EDIT: like the commenters below have said; this only works on events attached with jQuery, inline or in the style of "element.onclick". It does not work with addEventListener, and it will not follow the link if no event handlers are defined. You could solve this with something like this:

    var linkEl = $( 'link selector' );
    if ( linkEl.attr ( 'onclick' ) === undefined ) {
        document.location = linkEl.attr ( 'href' );
    } else {
        linkEl.click ();
    }
    

    Don't know about addEventListener though.

提交回复
热议问题