简体   繁体   中英

jQuery trigger click event not working on div

I want to trigger a click event on a div . I use the following code but it is not working.

$('#showbanner').trigger('click');
<div id="showbanner">show banner</div>

What is that I am doing wrong? I actually want to show the banner 2 seconds after page is loaded. Before I could add delay event my click event for this div is not firing.

Here is my code example: http://codepen.io/anon/pen/aOzyxo

The issue is because your trigger('click'); call is the first thing in your script; it's called before the event is attached.

You need to move it to the end of the script so that the event handlers are bound when it is called:

Updated Codepen

enter code here

Try this .

$(function () {


    $(document).on("click", "#showbanner", function () {
        alert('Hola');
    });

    $("#showbanner").click();

});
show banner

Try this

JS

$('#showbanner').on("click", function() { 
 alert("test");
});

$('#showbanner').trigger('click');

HTML

<div id="showbanner">show banner</div>

Try this

 $('#showbanner').on("click", function() { alert("test"); }); $('#showbanner').click(); 

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