javascript函数的基础功能

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

 <head>

  <title> New Document </title>

  <meta name="Generator" content="EditPlus">

  <meta name="Author" content="">

  <meta name="Keywords" content="">

  <meta name="Description" content="">

 </head>



 <body>



  <button onclick="test()">Button</button>



  <script type="text/javascript">

  var test = function()

  {

     document.write("javascript");

  }

  </script>

 </body>

</html>


点击按钮后就会显示javascript。这里设置了一个监听,点击onclick,会执行test的内容,但有一点应该知道,onclick的属性值并不是简单的函数名,而是可以放多条语句,以下写法也是正确的:

  <button onclick="document.write('javascript');

                   document.write('maybe');">Button</button>


点击后的结果为javascriptmaybe,所以千万不要误以为onclick的值是函数。

 

但是有的时候,我们onclick 和 script脚本写在html里,更改后的html如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

 <head>

  <title> New Document </title>

  <meta name="Generator" content="EditPlus">

  <meta name="Author" content="">

  <meta name="Keywords" content="">

  <meta name="Description" content="">

 </head>



 <body>

  <button id="button1">Button</button>





  <script type="text/javascript" src="maybe.js">

  </script>

 </body>

</html>


新建一个javascript文件,文件名为src属性的值maybe.js代码如下:

var test = function ()

{

	document.write("i am the one");

};



document.getElementById("button1").onclick = test;

 

运行结果:i am the one。注意被document添加的相应只能是一个函数,所以等号右边是test,而不是test();如果写成test();我们还需要设置一个返回值,比如:

var test = function ()

{

	document.write("i am the one");



	return function()

	{

		document.write("i am the two");

	}

};



document.getElementById("button1").onclick = test();

执行过程如图所示:

 

i am the one的出现应该不难理解,因为test() 就代表了函数的执行。

 

 

 

 

 

 

 

你可能感兴趣的:(JavaScript)