JS in the BOM related knowledge point Summary (Must see article) _javascript Skill

Source: Internet
Author: User
Tags hash numeric object model setinterval time in milliseconds browser cache

Window object

ECMAScript is the core of JavaScript, but if you want to use JavaScript on the web, then the BOM (browser object model) is the real core. The BOM provides a number of objects that are used to access the functionality of the browser, regardless of the content of any Web page.

Window object: The core object of the BOM is window, which represents an instance of the browser. In the browser, the Window object has a dual role, which is both an interface to access the browser window through JavaScript and a ECMAScript-defined global object.

Therefore, variables and functions declared in all global scopes become properties and methods of the Window object.

<script type= "Text/javascript" >
  var age=26;//the global variables and global functions defined here are automatically grouped under the Window object name
  function Sayage () {
    Console.log (this.age);
  }
  Console.log (window.age);//26 sayage ()//26 equivalent Window.sayage () window.sayage ()//26

  // The only difference between global variables and the direct definition of properties on a Window object: Global variables cannot be deleted by the delete operator, while properties defined directly on the Window object can be
  window.color= ' red ';
  Delete window.age;
  Delete Window.color;
  Console.log (window.age);//26
  Console.log (window.color);//undefined
  </script>
<script type= "Text/javascript" >
    /* Also note that attempting to access an undeclared variable throws an error, but by querying the Window object, you can tell if a variable exists that might be undeclared.
    //This throws an error because OldValue does not define the
    var Newvalue=oldvalue;
    This does not throw an error because it is a property query
    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, you can access the corresponding Window object through a numeric index (starting from 0, left to right, top to bottom), or frame name. Each Window object has a Name property that contains the names of the frames.

You can refer to the above frame by window.frames[0] or window.frames["Topframe". However, it is a good idea to use top instead of window to refer to these frames. Because the top object always points to the frame of the highest (most outer) layer, the browser window. Use it to ensure that another framework is properly accessed in one frame. Because for any code written in the framework, the window object points to a specific instance of that frame, not to the top-level frame.

Another window object relative to top is parent. The parent object always points to the immediate upper-level frame of the current frame.

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

In the case of a framework, there are multiple global objects in the browser. The global variables defined in each frame automatically become properties of the Window object in the frame. Because each Window object contains a primitive type of constructor, each frame has its own constructor, which is one by one corresponding, but not equal.

Location objects

The Location object is a very special object because it is both a property of the Window object and a property of the Document object. Window.location and Document.location refer to the same object.

Properties of the Location object:

<! DOCTYPE html>  

There are many ways you can change the position of a browser by using the Location object.

The most common way is to use the Assign () method and pass a URL to it

Location.assign ("Http://www.jb51.net")

This allows you to immediately open a new URL and generate a record in the browser's history.

Similarly, the location.href and window.location are set to a URL value, and the Assign () method is also invoked with that value.

Location.href= "Http://www.jb51.net";
Window.location= "Http://www.jb51.net";

The effect of both methods is exactly the same as the display call assign () method

In addition, you can change the currently loaded page by modifying other properties of the Location object.

Each time you modify the location properties (except for the hash), the page is reloaded with the new URL. Modifying the hash value will generate a new record in the browser's history

In the Url:http://a.com#helloword ' #helloworld ' is location.hash, changes the hash does not cause the page to refresh, therefore may use the hash value to carry on the data transmission, certainly the data capacity is limited.

When you modify a URL in either of these ways, a new record is generated in the browser's history, so you can navigate to the previous page by clicking the Back button.

We can use the Replace () method to disable this behavior. The method takes only one parameter, the URL to navigate to, and results in a change in the browser location, but does not generate a new record in the history. After the replace () method is invoked, the user cannot go back to the previous page.

When this page is loaded into the browser, the browser redirects to Www.jb51.net after 1 seconds. Then, the ' Back ' button is disabled, and if you re-enter the full URL, you cannot return to the sample page.

<script type= "Text/javascript" >
    settimeout (function () {
      location.replace ("http://www.jb51.net/");
    } , 1000);
  </script>

The reload () method, which is used to reload the currently displayed page. If you call the reload () method without passing any arguments, the page is 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 the method.

Location.reload ()//reload (it is possible to load from the cache)
Location.reload (TRUE);//reload (reload from server)

Timeout calls and intermittent calls

JavaScript is single-threaded, but allows the code to be set at a specific time by setting the timeout and intermittent values

Timeout call: Executing code after a specified time

Intermittent Invocation: Code executes once at specified intervals

Timeout call: You need to use the settimeout () method of the Window object to receive two parameters: the code to execute and the time in milliseconds.

The second parameter is a number of milliseconds that represents how long to wait, but the code specified after that time does not necessarily execute. Because JavaScript is a single-threaded interpreter, only a piece of code can be executed within a certain amount of time. The second parameter indicates that the current task is added to the queue for too long. If the queue is empty, the code executes immediately, or it waits until the previous code is finished executing.

When settimeout () is invoked, the method returns a numeric ID that represents the timeout call. To cancel a time-out call plan that is not executed, you can call the Cleartimeout () method and pass the appropriate timeout call ID as a parameter to it.

Intermittent invocation: Using the SetInterval () method

is similar to a timeout call, except that it repeats the code at a specified interval until the intermittent call is canceled or the page is unloaded. It receives the same parameters as the settimeout () method

Demo1

<script type= "Text/javascript" >
    //Set timeout call
    var timeoutid = settimeout (function () {
      alert ("Hello World! ");
    }, 1000);
    Cancels timeout call
    cleartimeout (Timeoutid);
  </script>

Demo2

<script type= "Text/javascript" >
  /* Using intermittent calls to achieve
   * *
    var num = 0;
    var max = ten;
    var intervalid = null;
    function Incrementnumber () {
      num++;
      if (num = max) {
        clearinterval (intervalid);
        Alert ("Done");
      }
    Intervalid = SetInterval (incrementnumber);
  </script>

Demo3

<script type= "Text/javascript" >
  /* uses a timeout call to implement
   *
    /var num = 0;
    var max = m;
    function Incrementnumber () {
      num++;
      if (num < max) {
        settimeout (incrementnumber);
      } else {
        alert ("Done");
    } SetTimeout (incrementnumber);
  </script>

When using a time-out call, there is no need to trace the timeout call ID, because after each execution of the code, the call stops automatically if another timeout call is no longer set. It is generally thought that using time-out to simulate intermittent calls is the best model. Intermittent calls are generally less used because the latter intermittent call may start before the end of the previous intermittent call.

System dialog box

Alert (), confirm () and prompt ()

<script type= "Text/javascript" >
    alert ("Hello world!");
  </script>



<script type= "Text/javascript" >
  /* To
  determine whether the user clicked OK or cancel, you can check confirm () Method returns a Boolean value of: True indicates that Ok,false was clicked to cancel or clicked the X button in the upper-right corner.
   *
    /if (Confirm ("Are you sure?")) {
      alert ("I ' m so glad ' re sure!");
    } else {
       alert ("I ' m sorry to hear for you ' re not sure.");
    }
  </script>



<script type= "Text/javascript" >
  /* Prompt () method is used to generate a "hint" box that prompts the user to enter some text. The prompt box displays a text entry field to enter text content in addition to the OK and Cancel buttons. The method receives two parameters: the default value (which can be an empty string) for text prompts and text input fields to be displayed to the user/
    var result = prompt ("What is your name?", "");
    if (result!== null) {
     alert (' Welcome, ' + result);
    }
  </script>

History objects

The history object holds the history of the user's Internet access, from the moment the window is opened. Because history is a property of the Window object, each browser window, every tab, and each frame has its own history object associated with a particular window object. In security terms, developers are not aware of the URLs that users have browsed, but the list of pages visited by the user can also be backed up and forward without knowing the actual URL.

You can use the Go () method to jump any way in the user's history, and you can go backwards and forwards. The method receives a parameter: An integer value that represents the number of pages that forward or backward jump. A negative number indicates a backward jump (similar to the Back button for clicking the browser), and a positive number indicates a forward jump (similar to the browser's forward button).

Back one page
    history.go ( -1);
    Forward one page
    history.go (1);

You can also pass a string argument to the Go () method, at which point the browser jumps to the first position in the history that contains the string – perhaps backwards or forwards, depending on which position you are in recently. If the history does not contain the string, then this method does nothing

Jump to the nearest jb51.net
history.go ("jb51.net");

Alternatively, you can use back () and forward () instead of the Go () method

Back one page
    history.back ();
    Forward one page
    history.forward ();

In addition, the history object also has a length property that holds the number of history records. This number includes all the history records, that is, all the backward and forward records. If history.length==0, it means that this is the first page after the user opens the window

History objects are not commonly used, but must be used when creating a custom back and forward button and detecting whether the current page is the first page of a user's history.

Demo1

History.html

<! DOCTYPE html>
 
 

Ceshi.html

<! DOCTYPE html>
 
 

This uses history to mimic a username after a user name is entered. Jump to the previous page example.

Demo2
History2.html

<! DOCTYPE html>
 
 

Demo.html

<! DOCTYPE html>
 
 

This small example simulates the basic functions of history.back () and History.forward ()

The above is small series for everyone to bring the knowledge of the BOM related to the summary (must see article) all content, I hope that we support cloud Habitat Community ~

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.