[英]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.