javascript學習筆記(2)

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有了更深的認識,也是最核心的認識。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章