简体   繁体   中英

Simulate clicking a button

If I have an existing click event associated with a button, can I use code to simulate that button being pressed so the code in the click event will run? I'm asking because I want there to be certain times where the user does not have to press the button for code to be executed. I would like to press the button automatically for them in certain instances if that makes any sense.

Three Choices:

  1. You can call the click event handling function directly when appropriate:

     if(timeIsRightForClick){ yourClickHandler(); }
  2. You can simulate a button click by calling the .click() method of the button.

     $("#ButtonID").click()

https://api.jquery.com/click/

  1. Same as #2, but using jQuery's trigger() function, which can be used on standard events and custom ones:

     $("#ButtonID").trigger("click");

http://api.jquery.com/trigger/

Choices #2 and #3 are usually better because they will cause the event handling function to receive a reference to the click event in case it needs to use that object. Choice #1 doesn't cause an actual click event (just runs the code you tell it to) and so no event object is created or passed to the event handler.

As simple as this,

$(function() {
    $('#button').trigger('click');
});

You can trigger a click event on an element by calling the .click() function on the element. By passing no value to the function the click event will fire, as opposed to setting up a listener for the click event.

If the button has an id of "form-btn", here's what that would like:

<button id="form-btn">Submit</button>

<script type="text/javascript">
    //Setup the click event
    $('#form-btn').on('click', function (e) {
        alert('clicked!');
    });

    //Call the click event
    $('#form-btn').click();
</script>

This should work fine, although I usually try to use a named function when setting up my event handlers, instead of anonymous functions. By doing so, rather than triggering the event I can call the function directly.

Note that in my experience, older browsers (IE6, IE7) sometimes limit what code-triggered events can do as a safety precaution for the user.

Here's documentation on the .click() function: http://www.w3schools.com/jquery/event_click.asp


Edit 1

I forgot that jQuery also has the .trigger() function, as used in choz 's answer. That will also the job quite nicely as an alternative to .click(). What's nice about .trigger() is that it can trigger standard events as well as custom events, and also allow you to pass more data in your event.

var button = document.getElementById('yourButtonIdHere');
button.click();

This will fire a click event in the button

只需创建一个函数并从按钮内运行该函数即可。

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