在 html 中调用 javascript 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31510608/
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
calling javascript function inside html
提问by Paulo Neil Corpuz
<html>
<head>
</head>
<body>
<script>
var myFunction = function(){
return "hello world";
}
</script>
myFunction();
</body>
</html>
I just finished the code academy course on javascript but it didn't taught me how to code javascript inside html. I need to display hello world inside the html's tag using the function is this possible? my friend told me I need jquery just to do this.
我刚刚完成了关于 javascript 的代码学院课程,但它没有教我如何在 html 中编写 javascript。我需要使用该函数在 html 的标签内显示 hello world 这可能吗?我的朋友告诉我我需要 jquery 来做到这一点。
回答by Loic
You have to specifically tell the webpage to execute your function when it's loaded.
您必须明确告诉网页在加载时执行您的功能。
Instead of returning the string I believe you'd like to write it in the body of the webpage.
我相信您希望将它写在网页正文中,而不是返回字符串。
This is a simple way to do so :
这是一个简单的方法:
<html>
<head>
<script>
var myFunction = function(){
document.body.innerHTML = "hello world";
}
</script>
</head>
<body onload='myFunction();'>
</body>
</html>
回答by Vishnu Prasad
Try this
尝试这个
<html>
<head>
</head>
<body onload='myFunction()'>
<script type="text/javascript">
var myFunction = function(){
return "hello world";
}
</script>
</body>
</html>
回答by Paulo Neil Corpuz
<html>
<head>
</head>
<body>
<Script>
function myFunction(){
document.write("hello");
}
</script>
<Script>
myFunction();
</Script>
</body>
</html>
This was asked already How to call a javascript function within an HTML body
这已经被问到 如何在 HTML 正文中调用 javascript 函数
I just replace the
我只是更换
tag with document.write
用 document.write 标记