A function is a set of statements that perform a specific function. Without functions, it might take five, ten, or even more lines of code to accomplish a task.
At this time, we can put the code block that completes a specific function into a function, and call this function directly, saving the trouble of repeatedly entering a large amount of code.
How to define a function? The basic syntax is as follows:
function functionName()
{
function task here;
}
illustrate:
function
keyword is used to define a function.- "Function Name" is the name you give to the function.
- "Function task" is the code that completes the specific function.
Let's write a simple function to add two numbers, and give the function a meaningful name: "add2", the code is as follows:
function add2(){
var sum = 3 + 2;
alert(sum);
}
function call:
After the function is defined, it cannot be executed automatically, so it needs to be called. The code below uses button to call the function.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Javascript function - define and call</title>
<script type="text/javascript">
// function to add two numbers
function add2() {
var sum = 3 + 2;
alert(sum);
}
</script>
</head>
<body>
<form>
<input type="button" value="Add number" onclick="add2()">
<!-- call the function add2 when the button is clicked -->
</form>
</body>
</html>
Task - Exercise 9
Complete the code in line 7 and 15 to have a complete and working function.
There is a button (named "Click me") in the webpage, when the button is clicked, the function contxt() is called, and a dialog box "haha, the function is called!" pops up.
Task Code
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Function call</title>
<script type="text/javascript">
contxt() //Definition function
{
alert("Haha, the function is called!");
}
</script>
</head>
<body>
<form>
<input type="button" value="click me" onclick=" " />
</form>
</body>
</html>
//= htmlentities($post["body"]); ?>