How do I simulate user clicking a link in JQuery?

前端 未结 4 1186
傲寒
傲寒 2021-01-02 19:49

Now there\'s quite a lot of similar-looking questions here, but I was wondering, what should I do, if I want not to just change the location of the window, but

相关标签:
4条回答
  • 2021-01-02 20:28

    Try a[0].click();

    This will execute the click method of the DOM element instead of triggering the event.

    0 讨论(0)
  • 2021-01-02 20:42

    Yes, very simple:

    $('#YourSelector').click();
    

    this will emulate a user click.

    0 讨论(0)
  • 2021-01-02 20:44

    In IE, you can call .click() on the element, but for standard browsers you need to simulate the click event by creating a native mouse event and then use dispatchEvent to trigger it.

    I summed it all up in this jQuery 'plugin':

    $.fn.simulateClick = function() {
        return this.each(function() {
            if('createEvent' in document) {
                var doc = this.ownerDocument,
                    evt = doc.createEvent('MouseEvents');
                evt.initMouseEvent('click', true, true, doc.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
                this.dispatchEvent(evt);
            } else {
                this.click(); // IE
            }
        });
    }
    

    Now, just call:

    $('.edithost').simulateClick();
    
    0 讨论(0)
  • 2021-01-02 20:46

    I don't really get what you want to do. with this :

    a.click(function(e){
    e.preventDefault();
    });
    

    You can stop the default behaviour of the event (in this case, redirecting to a.attr('href')). You can then perform whatever task you want and then redirect the user manually.

    Is this what you're looking for ?

    If you want to trigger the click event, just do

    a.click();
    
    0 讨论(0)
提交回复
热议问题