最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Trigger click function on load - Stack Overflow

programmeradmin0浏览0评论

I have the following function which is activated on click:

$('.results .view-rooms').click(function(){   }

Is there anyway I can trigger this function on document load?

I have the following function which is activated on click:

$('.results .view-rooms').click(function(){   }

Is there anyway I can trigger this function on document load?

Share Improve this question edited May 31, 2012 at 20:29 gdoron 150k59 gold badges302 silver badges371 bronze badges asked May 31, 2012 at 20:21 user1038814user1038814 9,65718 gold badges68 silver badges88 bronze badges 1
  • document ready or window load you mixed them... :) – gdoron Commented May 31, 2012 at 20:29
Add a comment  | 

7 Answers 7

Reset to default 8

Yes.

$(document).ready(function(){ // on document ready
    $(".results .view-rooms").click(); // click the element
})
$('.results .view-rooms').click()

You can put it in DOM ready:

$(function(){
    $('.results .view-rooms').click()
});

Or window load:

$(window).load(function(){
    $('.results .view-rooms').click();
});

Note that there is no such event document load.
We have DOM ready or window load

$(document).ready(function(){ $('.results .view-rooms').click(); });

Considering that you're already using jQuery to bind the event handler, and assuming that code is already in a position where the entire DOM has been constructed, you can just chain the call to .click() to then trigger that event handler:

$('.results .view-rooms')
                        .click(function(){...}) //binds the event handler
                        .click(); // triggers the event handler

Put the code inside

$(function(){ // code here  }); 

like:

$(function(){ 
   $(".results .view-rooms").click(); 
});

or

$(function(){ 
   $(".results .view-rooms").trigger('click'); 
});
$(function(){

    $('.results .view-rooms').click(function(){ 

    }

    $(".results .view-rooms").trigger('click');

}

The best way is:

html form:

<form action="https://stackoverflow.com" method="get">
  <button id="watchButton"></button>
</form>

End Jquery:

<script>
   $('document').ready(function() {
     $('#watchButton').click();
   });
</script>

JQuery Version:

https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js
发布评论

评论列表(0)

  1. 暂无评论