简体   繁体   English

如何在页面加载时单击按钮元素

[英]How to click a button element on page load

I have created 5 buttons. 我创建了5个按钮。 I'm loading some pages on button click. 我在单击按钮时加载了一些页面。 I want the first button automatically clicked on page load and load it's corresponding html file and the remaining buttons should load html files only on clicking them. 我希望第一个按钮在页面加载时自动单击并加载其相应的html文件,其余按钮仅在单击它们时才应加载html文件。 Someone help me!! 谁来帮帮我!!

This is my jquery: 这是我的jQuery:

$('a#Home').click(function() {
  $("#home").load("x.html");
});

$('a#Menu1').click(function() {
  $("#menu1").load("y.html");
});

$('a#Menu2').click(function() {
  $("#menu2").load("z.html");
});

$('a#Menu3').click(function() {
  $("#menu3").load("searcharray.html");
});

$('a#Menu4').click(function() {
  $("#menu4").load("sortarray.html");
});

Just test this code. 只需测试此代码。 I think this will help you. 我认为这会对您有所帮助。

 $( document ).ready(function() { console.log( "ready!" ); $('#btn1').trigger( "click" ); }); function fun1() { alert('loaded'); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="btn1" onclick="fun1()">btn1</button> <button id="btn2">btn1</button> <button id="btn3">btn1</button> <button id="btn4">btn1</button> 

Assuming the first button is Home then you want run that on document ready by using $(function() 假设第一个按钮是家庭,那么你想要运行在文件准备使用$(function()

<script>
    $(function() {
        $('a#Home').click();
    });

    function loadHome() {
        $("#home").load("x.html");
    };
</script>

Then update your link to be like: 然后将您的链接更新为:

<a id="Home" onclick="loadHome()">Click Me</a>

trigger the event yourself: 自己触发事件:

$('a#Home').click(function() {
  $("#home").load("x.html");
});
$('a#home').trigger('click');

Theoretical answer 理论答案

You can trigger any event on any element using the .trigger() method. 您可以使用.trigger()方法在任何元素上触发任何事件。 This will require you to specify which event you want to fire. 这将要求您指定要触发的事件。 More information. 更多信息。

It is also possible to trigger a click event just by calling .click() after binding the event handling. 绑定事件处理后,也可以仅通过调用.click()来触发click事件。 The documentation shows us that we can use this function for both purposes. 该文档向我们展示了我们可以同时使用此功能。

$( document ).ready() is an interaction that can be used to run code once when the document has been loaded. $( document ).ready()是一种可以在加载文档后运行一次代码的交互。 More info on that can be found here. 有关更多信息,请参见此处。

Examples 例子

Example #1 (using .trigger() ) 示例1(使用.trigger()

$( document ).ready(function() {
    $('a#Home').trigger('click');
});

Example #2 (using .click() ) 示例2(使用.click()

$( document ).ready(function() {
    $('a#Home').click();
});

You can try this: 您可以尝试以下方法:

 <script>
       function pageLoad()
{
    alert('hello');
}

pageLoad();

 </script>


<button id="btn1" onclick="pageLoad()">btn1</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM