JavaScript封闭函数及常用内置对象示例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

JavaScript封闭函数及常用内置对象示例

SpecYue   2020-05-17 我要评论

本文实例讲述了JavaScript封闭函数及常用内置对象。分享给大家供大家参考,具体如下:

封闭函数

在封闭函数内部定义的函数与外部函数尽管同名也没有关系,同理,定义的变量也可以同名。

封闭函数的写法,一是加括号,一是加感叹号。

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>封闭函数</title>
 <script type="text/javascript">
  var num = 22;
  function f() {
   alert("hello ");
  }
  (function () {
   var num = 11;
   function myalter() {
    alert("hello world");
   }
   alert(num);
   myalter()
  })();
  /*封闭函数的第二种写法,前面加一个感叹号或者加一个波浪线*/
  !function(){
   alert("ll");
  }();
  alert(num)
 </script>
</head>
<body>
<div>
 55
</div>
</body>
</html>

常用内置对象

1.document

document.getElemntsByTagName 通过标签名获取元素
document.getElementsById 通过id获取元素
document.referrer 获取上一个跳转页面的地址

2.location

window.location.href 获取或者重定向url地址
window.location.search 获取地址参数部分
window.location.hash 获取页面锚点或者叫hash值

<meta charset="UTF-8">
 <title>常用内置对象</title>
 <script type="text/javascript">
  /*
  * 1.document
  * document.getElemntsByTagName 通过标签名获取元素
  * document.getElementsById 通过id获取元素
  * document.referrer 获取上一个跳转页面的地址
  *
  * 2.location
  * window.location.href 获取或者重定向url地址
  * window.location.search 获取地址参数部分
  * window.location.hash 获取页面锚点或者叫hash值
  *
  * */
  window.onload = function () {
   var sUrl = document.referrer;
   /*获取服务器地址,或者说上一个页面地址*/
   var oBtn = document.getElementById("btn01");
   oBtn.onclick = function () {
    window.location.href = sUrl;
    /*但是因为不是服务器地址所以存不下来,这边可以直接写百度网址的字符串*/
   };
   var oBody = window.getElementById('body01');
   var sData = window.location.search;
   /*http://localhost:63342/Javascirpt/%E5%B8%B8%E7%94%A8%E5%86%85%E7%BD%AE%E5%AF%B9%E8%B1%A1.html?_ijt=1
   * 如上是访问页面的地址,在最后?问好后面的就是参数,在开放中可以根据不同的参数,使得页面表现形式不一样。
   * 比如现在参数是1
   * 我们得到body的属性,让他的背景颜色变成金色
   * */
   var aRr = sData.split("=");
   var iNum = aRr[1];
   if (iNum == 1) {
    oBody.style.backgroundColor = "gold";
   }
   // if(sData!=null)
   // {
   //  alert(sData);
   // }
   alert(sData);
   /*获取地址参数*/
  }
 </script>
</head>
<body id='body01'>
<input type="button" name="" value="跳转" id="btn01">
</body>
</html>

http://localhost:63342/Javascirpt/常用内置对象.html?_ijt=1

如上是访问页面的地址,在最后?问好后面的就是参数,在开放中可以根据不同的参数,使得页面表现形式不一样。

比如现在参数是1

我们得到body的属性,让他的背景颜色变成金色

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Document</title>
</head>
<body>
 <a href="常用内置对象.html" rel="external nofollow" >链接到常用内置对象的页面</a>
 <a href="常用内置对象.html?aa=1" rel="external nofollow" >链接到常用内置对象的页面1</a>
 <a href="常用内置对象.html?aa=2" rel="external nofollow" >链接到常用内置对象的页面2</a>
 <a href="常用内置对象.html?aa=3" rel="external nofollow" >链接到常用内置对象的页面3</a>
</body>
</html>

传递不同的参数改变页面的状态。

希望本文所述对大家JavaScript程序设计有所帮助。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们