zoukankan      html  css  js  c++  java
  • 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() 就代表了函数的执行。

  • 相关阅读:
    Web 2.0网站命名的7个建议
    梦猪课堂视频系列
    计算机英文术语完全介绍
    PPT高手的思路
    在线RSS阅读器大比拼
    【百度现有服务】
    转载VFW编程实例(详)
    实现MFC扩展DLL中导出类和对话框 (转)
    Windows下编译 OpenSceneGraph(转)
    OSG静态编译 (转)
  • 原文地址:https://www.cnblogs.com/james1207/p/3323021.html
Copyright © 2011-2022 走看看