javascript中的函数是很重要的一部分内容,所以在此小试牛刀的练习下函数使用的相关内容。
简单函数:
语法:
将脚本编写为函数,就可以避免页面载入时执行该脚本。
函数包含着一些代码,这些代码只能被事件激活,或者在函数被调用时才会执行。
你可以在页面中的任何位置调用脚本(如果函数嵌入一个外部的 .js 文件,那么甚至可以从其他的页面中调用)。
函数在页面起始位置定义,即 <head> 部分。
代码:
<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!")
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!" onclick="displaymessage()
" >
</form>
</body>
</html>
带有参数的函数:
语法:
<html>
<head>
<script type="text/javascript">
function myfunction(txt)
{
alert(txt)
}
</script>
</head>
<body>
<form>
<input type="button"
onclick="myfunction('Hello')"
value="Call function">
</form>
<p>By pressing the button, a function with an argument will be called. The function will alert
this argument.</p>
</body>
</html>
带有参数的函数2
<html>
<head>
<script type="text/javascript">
function myfunction(txt)
{
alert(txt)
}
</script>
</head>
<body>
<form>
<input type="button"
Morning!')"
value="In the Morning">
<input type="button"
Evening!')"
value="In the Evening">
</form>
<p>
When you click on one of the buttons, a function will be called. The function will alert
the argument that is passed to it.
</p>
</body>
</html>
返回值的函数:
<html>
<head>
<script type="text/javascript">
function myFunction()
{
return ("Hello, have a nice day!")
}
</script>
</head>
<body>
<script type="text/javascript">
document.write(myFunction())
</script>
<p>The script in the body section calls a function.</p>
<p>The function returns a text.</p>
</body>
</html>
带有参数并返回值的函数
<html>
<head>
<script type="text/javascript">
function product(a,b)
{
return a*b
}
</script>
</head>
<body>
<script type="text/javascript">
document.write(product(4,3))
</script>
<p>The script in the body section calls a function with two parameters (4 and 3).</p>
<p>The function will return the product of these two parameters.</p>
</body>
</html>
后面的直接剪切代码上去,不想截图,但是通过这些个练习对javascript有了更深的认识,也是最核心的认识。