简体   繁体   中英

How to trigger click on page load?

I'm looking for a way to automatically "click" an item when the page loads.

I've tried using

$("document").ready(function() {
    $("ul.galleria li:first-child img").trigger('click');
});

but it doesn't seem to work? However, when I enter $("ul.galleria li:first-child img").trigger('click'); into Firebug's console and run the script, it works.

Can the trigger event be used on load?

The click handler that you are trying to trigger is most likely also attached via $(document).ready()<\/code> . What is probably happening is that you are triggering the event before the handler is attached. The solution is to use setTimeout<\/code> :

$("document").ready(function() {
    setTimeout(function() {
        $("ul.galleria li:first-child img").trigger('click');
    },10);
});
$(function(){

    $(selector).click();

});
$("document").ready({
    $("ul.galleria li:first-child img").click(function(){alert('i work click triggered'});
}); 

$("document").ready(function() { 
    $("ul.galleria li:first-child img").trigger('click'); 
}); 

just make sure the click handler is added prior to the trigger event in the call stack sequence.

  $("document").ready(function() { 
        $("ul.galleria li:first-child img").trigger('click'); 
    }); 

   $("document").ready({
        $("ul.galleria li:first-child img").click(function(){alert('i fail click triggered'});
    }); 

try this,

$("document").ready(function(){

$("your id here").trigger("click");
});

You can do the following :-

$(document).ready(function(){
    $("#id").trigger("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