当我想调用它时,如何在主体中调用 <head> 中声明的 JavaScript 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8773633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call a JavaScript function, declared in <head>, in the body when I want to call it
提问by user1110666
I have a working JavaScript function declared in the head of an HTML page. I know how to create a button and call the function when the user clicks the button. I want to call it myself some where on the page:
我在 HTML 页面的头部声明了一个有效的 JavaScript 函数。我知道如何创建按钮并在用户单击按钮时调用该函数。我想自己在页面上的某个地方称它为:
myfunction();
How do I do it?
我该怎么做?
回答by Minko Gechev
You can call it like that:
你可以这样称呼它:
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
var person = { name: 'Joe Blow' };
function myfunction() {
document.write(person.name);
}
</script>
</head>
<body>
<script type="text/javascript">
myfunction();
</script>
</body>
</html>
The result should be page with the only content: Joe Blow
结果应该是具有唯一内容的页面: Joe Blow
Look here: http://jsfiddle.net/HWreP/
看这里:http: //jsfiddle.net/HWreP/
Best regards!
此致!
回答by Doug
I'm not sure what you mean by "myself".
我不确定你所说的“我自己”是什么意思。
Any JavaScript function can be called by an event, but you must have some sort of event to trigger it.
任何 JavaScript 函数都可以被事件调用,但你必须有某种事件来触发它。
e.g. On page load:
例如在页面加载时:
<body onload="myfunction();">
Or on mouseover:
或者在鼠标悬停时:
<table onmouseover="myfunction();">
As a result the first question is, "What do you want to do to cause the function to execute?"
因此,第一个问题是,“您想做什么来使函数执行?”
After you determine that it will be much easier to give you a direct answer.
在您确定之后,直接给您答案会容易得多。
回答by j08691
Just drop
就放下
<script>
myfunction();
</script>
in the body where you want it to be called, understanding that when the page loads and the browser reaches that point, that's when the call will occur.
在您希望调用它的正文中,了解当页面加载并且浏览器到达该点时,即会发生调用。
回答by harsimranb
You can also put the JavaScript code in script tags, rather than a separate function. <script>//JS Code</script>
This way the code will get executes on Page Load.
您还可以将 JavaScript 代码放在脚本标签中,而不是单独的函数中。<script>//JS Code</script>
这样,代码将在页面加载时执行。