简体   繁体   English

如何制作在页面加载时执行的功能?

[英]How can I make a function which executes on page loading?

I have a JS function that I need to execute it when page loads. 我有一个JS函数,需要在页面加载时执行它。 Here is the function: 这是函数:

function myfunc(){
    alert('something');
}

Noted that I also need to have a name for it. 注意,我还需要为其命名。 Because I need to call it after page loading again (on click of a element) . 因为我需要在页面加载后(在单击元素时)再次调用它。

So in short, I need to define a function which executes both on page loading and when user click on $('.myclass') element. 简而言之,我需要定义一个在页面加载以及用户单击$('.myclass')元素时都执行的函数。 How can I do that? 我怎样才能做到这一点?

Put the call to that function in both the click handler for the .myclass elements, and also directly in a script tag, right before the </body> . 将该函数的调用放在.myclass元素的点击处理程序中,也直接放在</body>之前的script标记中。 Something like this: 像这样:

<script>
    $(function() {
        $('.myclass').click(myfunc); // on click
    });

    myfunc(); // on load
</script>

Try below code, It calls Click me on load and on button click as well. 尝试下面的代码,它在加载时也单击“单击我”,在按钮单击时也是如此。 Hope this helps 希望这可以帮助

 $(document).ready(function() { console.log('document load') clickMe(); }); $('.button').click(function(){ clickMe(); }); function clickMe(){ console.log('Clicked'); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button class="button" > click me</button> 

how about <body onload="myfunc()"> and your function in the <head> element: <body onload="myfunc()"><head>元素中的函数怎么样:

<script>
function myfunc(){
    alert('something');
}
</script>

and then to call it from button 然后从按钮调用它

<button onclick="myfunc()">Click me</button>

暂无
暂无

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

相关问题 我如何编写一个函数,如果它的参数是节点集合,则为 javascript 中的所有节点元素执行? - How can i write a function, which if it's parameter is a node collection, executes for all node elements in javascript? 页面加载完成后如何调用函数 - How can I make a function get called after a page has finished loading 如何确保我的click函数只用Jquery执行一次? - How can I make sure that my click function executes one time only with Jquery? 滚动页面时如何加载动画内容 - How to i can make Animated Contents Loading while Scroll the page 即使我正在使用 $(window).on(&#39;load&#39;, function(),jQuery 也会在页面完成加载之前执行 - jQuery executes before page finishes loading even though I'm using $(window).on('load', function() 如何制作一个总是先执行到最后执行的脚本? - How can I make a script that always executes first to execute last? 只要执行 function ,如何让按钮成为加载按钮? - How can I make a button a loading button as long as the function is executed? 如何制作一个简单的firefox插件,该插件仅在每个新页面上执行独立的JS脚本? - How to make a simple firefox addon, which just executes stand-alone JS script on every new page? 如何在页面完成加载之前显示JavaScript加载图像? - How can I make a JavaScript loading image show until a page finishes loading? 如何在angularjs中使函数同步执行 - how to make a function in angularjs executes Synchronously
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM