Home  >  Article  >  Web Front-end  >  Summary of BOM related knowledge points in JS (must read)

Summary of BOM related knowledge points in JS (must read)

高洛峰
高洛峰Original
2016-12-06 09:52:56994browse

Window object

ECMAScript is the core of JavaScript, but if you want to use JavaScript in the web, then the BOM (Browser Object Model) is the real core. The BOM provides a number of objects for accessing browser functionality that are independent of any web page content.

window object: The core object of BOM is window, which represents an instance of the browser. In the browser, the window object has a dual role. It is not only an interface for accessing the browser window through javascript, but also a Global object specified by ECMAScript.

Therefore, all variables and functions declared in the global scope will become properties and methods of the window object.

<script type="text/javascript">
  var age=26;//这里定义的全局变量和全局函数被自动归在了window对象名下
  function sayAge(){
    console.log(this.age);
  }
  console.log(window.age);//26
  sayAge();//26 相当于window.sayAge()
  window.sayAge();//26
 
  //全局变量和在window对象上直接定义属性的唯一区别:全局变量不能够通过delete操作符删除,而直接在window对象上定义的属性可以
  window.color=&#39;red&#39;;
  delete window.age;
  delete window.color;
  console.log(window.age);//26
  console.log(window.color);//undefined
  </script>

<script type="text/javascript">
    /*
    还要注意:尝试访问未声明的变量会抛出错误,但是通过查询window对象,可以知道某个可能未经声明的变量是否存在
     */
    //这会抛出错误,因为oldValue未定义
    var newValue=oldValue;
    //这不会抛出错误,因为是一次属性查询
    var newValue=window.oldValue;
  </script>

Window relationships and frames

If the page contains frames, each frame has its own window object and is saved in the frames collection. In the frames collection, the corresponding window object can be accessed by numerical index (starting from 0, left to right, top to bottom) or frame name. Each window object has a name attribute, which contains the name of the frame.

You can reference the upper frame through window.frames[0] or window.frames["topFrame"]. However, it is better to use top instead of window to refer to these frames. Because the top object always points to the highest (outermost) frame, which is the browser window. Use this to ensure correct access from one frame to another. Because for any code written in a framework, the window object points to a specific instance of that framework, not the highest-level framework.

Another window object opposite to top is parent. The parent object always points to the frame directly above the current frame.

The last object related to the frame is self, which always points to the window. self and window objects can be used interchangeably.

When using frames, there will be multiple Global objects in the browser. Global variables defined in each frame automatically become properties of the window object in the frame. Since each window object contains a native type constructor, each framework has its own set of constructors, which correspond to each other but are not equal.

location object

The location object is a very special object because it is an attribute of both the window object and the document object. window.location and document.location refer to the same object.

Attributes of the location object:

Summary of BOM related knowledge points in JS (must read)

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>查询字符串参数</title>
</head>
<body>
<script type="text/javascript">
    function getQueryStringArgs(){
      //取得查询字符串并去掉开头的问号
      var qs = (location.search.length > 0 ? location.search.substring(1) : ""),
        //保存数据对象
        args = {},
        //取得每一项
        items = qs.length ? qs.split("&") : [],
        item = null,
        name = null,
        value = null,
        //在for循环中使用
        i = 0,
        len = items.length;
      //逐个将每一项添加到args对象中
      for (i=0; i < len; i++){
        item = items[i].split("=");
        //decodeURIComponent用来解码name和value,因为查询字符串应该是被编码过的
        name = decodeURIComponent(item[0]);
        value = decodeURIComponent(item[1]);
 
        if (name.length){
          args[name] = value;
        }
      }
      return args;
    }
    //假设查询字符串是: ?q=javascript&num=10
    var args = getQueryStringArgs();
    alert(args["q"]);   //"javascript"
    alert(args["num"]);  //"10"
    //这样一来,每个查询字符串参数都成了返回对象的属性,极大地方便了对每个参数的访问
</script>
</body>
</html>

Using the location object, you can change the location of the browser in many ways.

Among them, the most common way is: use the assign() method and pass it a URL

location.assign("http://www.php.cn")

This way you can open the new URL immediately and Generates a record in the browser's history.

Similarly, setting location.href and window.location to a URL value will also call the assign() method with this value.

location.href=”http://www.php.cn”;
window.location=”http://www.php.cn”;

The effect and display of these two methods call the assign() method The effect is exactly the same

In addition, the currently loaded page can also be changed by modifying other properties of the location object.

Summary of BOM related knowledge points in JS (must read)

Every time you modify the location attributes (except hash), the page will be reloaded with a new URL. Modifying the hash value will generate a new record in the browser's history. The '#helloworld' in the URL: http://a.com#helloword is location.hash. Changing the hash will not cause the page to refresh. , so hash values ​​can be used for data transfer. Of course, the data capacity is limited.

When the URL is modified through any of the above methods, a new record will be generated in the browser's history, so clicking the "Back" button will navigate to the previous page.

We can use the replace() method to disable this behavior. This method only accepts one parameter, which is the URL to be navigated to; although the result will cause the browser location to change, it will not generate a new record in the history. After calling the replace() method, the user cannot return to the previous page.

After this page is loaded into the browser, the browser will redirect to www.php.cn after 1 second. The 'Back' button will then be disabled and you will not be able to return to the example page if you re-enter the full URL.

<script type="text/javascript">
    setTimeout(function () {
      location.replace("http://www.php.cn/");
    }, 1000);
  </script>

reload() method, its function is to reload the currently displayed page. If you call the reload() method without passing any parameters, the page will be reloaded in the most efficient way. That is, if the page has not changed since the last request, the page will be reloaded from the browser cache. If you want to force a reload from the server, you need to pass the parameter true to this method.

location.reload();//Reload (possibly load from cache)

location.reload(true);//Reload (reload from server)


Timeout call and intermittent call

javascript是单线程语言,但允许通过设置超时值和间歇值来设定代码在特定时刻执行

超时调用:是在指定的时间过后执行代码

间歇调用:每隔指定的时间就执行一次代码

超时调用:需要使用window对象的setTimeout()方法,接收两个参数:要执行的代码和以毫秒表示的时间。

第二个参数是一个表示等待多长时间的毫秒数,但经过该时间后指定的代码不一定执行。因为,javascript是一个单线程的解释器,因此一定时间内只能执行一段代码。第二个参数表示再过多长时间把当前任务添加到队列中。如果队列是空的,则代码会立刻执行,否则就要等待前面的代码执行完了以后再执行。

调用setTimeout()后,该方法会返回一个数值ID,表示超时调用。要取消未执行的超时调用计划,可以调用clearTimeout()方法并将相应的超时调用ID作为参数传递给它即可。

间歇调用:使用setInterval()方法

与超时调用类似,只不过它会按照指定的时间间隔重复执行代码,直到间歇调用被取消或者页面被卸载。它接收的参数与setTimeout()方法一样

Demo1

<script type="text/javascript">
    //设置超时调用
    var timeoutId = setTimeout(function() {
      alert("Hello world!");
    }, 1000);
    //取消超时调用
    clearTimeout(timeoutId);
  </script>

   

Demo2

<script type="text/javascript">
  /*
  使用间歇调用实现
   */
    var num = 0;
    var max = 10;
    var intervalId = null;
    function incrementNumber() {
      num++;
      if (num == max) {
        clearInterval(intervalId);
        alert("Done");
      }
    }
    intervalId = setInterval(incrementNumber, 500);
  </script>

   

Demo3

   
<script type="text/javascript">
  /*
  使用超时调用来实现
   */
    var num = 0;
    var max = 100;
    function incrementNumber() {
      num++;
      if (num < max) {
        setTimeout(incrementNumber, 500);
      } else {
        alert("Done");
      }
    }
    setTimeout(incrementNumber, 500);
  </script>

   

在使用超时调用时,没有必要跟踪超时调用ID,因为每次执行代码之后,如果不再设置另一次超时调用,调用就会自动停止。一般认为,使用超时调用来模拟间歇调用是一种最佳模式。间歇调用一般较少使用,因为后一个间歇调用可能会在前一个间歇调用结束之前启动。

系统对话框

alert()、confirm()和prompt()

<script type="text/javascript">
    alert("Hello world!");
  </script>
 
 
 
<script type="text/javascript">
  /*
  判断用户点击了OK还是Cancel,可以检查confirm()方法返回的布尔值:true表示单击了OK,false表示单击了Cancel或单击了右上角的X按钮。
   */
    if (confirm("Are you sure?")) {
      alert("I&#39;m so glad you&#39;re sure! ");
    } else {
       alert("I&#39;m sorry to hear you&#39;re not sure. ");
    }
  </script>
 
 
 
<script type="text/javascript">
  /*
  prompt()方法用来生成一个"提示"框,用于提示用户输入一些文本。提示框除了显示OK和Cancel按钮之外 ,还会显示一个文本输入域,用来输入文本内容。该方法接收两个参数:要显示给用户的文本提示和文本输入域的默认值(可以是一个空字符串)
   */
    var result = prompt("What is your name? ", "");
    if (result !== null) {
     alert("Welcome, " + result);
    }
  </script>

   

history对象

history对象保存着用户上网的历史记录,从窗口被打开的那一刻算起。因为history是window对象的属性,因此每个浏览器窗口、每个标签页以及每个框架,都有自己的history对象与特定的window对象关联。处于安全方面的考虑,开发人员是无法知道用户浏览过的URL,不过,借助用户访问过的页面列表,同样可以在不知道实际URL的情况下实现后退和前进。

使用Go()方法可以在用户的历史记录中任意跳转,可以向后也可以向前。该方法接收一个参数:表示向前或者向后跳转的页面数的整数值。负数表示向后跳转(类似单击浏览器的后退按钮),正数表示向前跳转(类似浏览器的前进按钮)。

//后退一页
    history.go(-1);
    //前进一页
    history.go(1);

   

也可以给go()方法传递一个字符串参数,此时浏览器会跳转到历史记录中包含该字符串的第一个位置–可能后退也可能前进,具体要看哪个位置最近。如果历史记录中不包含该字符串,那么这个方法什么也不做

//跳转到最近的php.cn
history.go("php.cn");

   

另外,还可以使用back()和forward()来代替go()方法

//后退一页
    history.back();
    //前进一页
    history.forward();

   

除此之外,history对象还有一个length属性,保存着历史记录的数量。这个数量包括所有的历史记录,即所有的向后和向前的记录。如果history.length==0,则表示这是用户打开窗口后的第一个页面

history对象不常用,但是在创建自定义的后退和前进按钮,以及检测当前页面是不是用户历史记录的第一个页面时,还是必须使用它。

Demo1 

history.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>history</title>
</head>
<body>
  <form>
    <input type="text" id="username">
  </form>
  <input type="button" id="btn" value="按钮" onclick="go()">
  <script type="text/javascript">
    function go(){
      var name=document.getElementById("username").value;
      if(name=="hello"){
        history.go(-1);
      }else{
        alert(&#39;用户名不正确&#39;);
      }
    }
  </script>
</body>
</html>

   

ceshi.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title></title>
  <link rel="stylesheet" href="">
</head>
<body>
  <a href="history.html" >跳转</a>
</body>
</html>

   

这里使用history模仿了一个输入用户名之后。跳转到之前页面的例子。

Demo2 
history2.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>history</title>
</head>
<body>
  <a href="demo.html">跳转</a>
  <input type="button" id="btn" value="前进" onclick="go()">
  <script type="text/javascript">
    function go(){
      history.forward();
    }
  </script>
</body>
</html>

   

demo.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title></title>
  <link rel="stylesheet" href="">
</head>
<body>
  <input type="button" name="" value="回退" id="btn" onclick="fn()">
  <script type="text/javascript">
    function fn(){
      history.back();
    }
  </script>
</body>
</html>

   

这个小例子模拟了history.back()和history.forward()的基本功能


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn