• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
james1207

博客园    首页    新随笔    联系   管理    订阅  订阅

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() 就代表了函数的执行。

 

 

 

 

 

 

 

posted @ 2013-09-15 19:37  Class Xman  阅读(166)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3