Simulate a click on 'a' element using javascript/jquery

前端 未结 8 2264
别跟我提以往
别跟我提以往 2020-12-04 17:08

I am trying to simulate a click on on an element. HTML for the same is as follows



        
8条回答
  •  遥遥无期
    2020-12-04 18:07

    The code you've already tried:

    document.getElementById("gift-close").click();
    

    ...should work as long as the element actually exists in the DOM at the time you run it. Some possible ways to ensure that include:

    1. Run your code from an onload handler for the window. http://jsfiddle.net/LKNYg/
    2. Run your code from a document ready handler if you're using jQuery. http://jsfiddle.net/LKNYg/1/
    3. Put the code in a script block that is after the element in the source html.

    So:

    $(document).ready(function() {
        document.getElementById("gift-close").click();
        // OR
        $("#gift-close")[0].click();
    });
    

提交回复
热议问题