《javascript Introduction to classics 》-day02

1. Using functions

1.1 Basic grammar

function sayHello() {
//... Other statements ...

# On function parameters , Formal parameters and actual parameters and other issues will not be discussed , Later chapters will focus on this issue .

# On the scope of function variables , Follow up python And advanced JavaScript Detailed discussion

2.DOM Objects and built-in objects

2.1 Interact with users

2.1.1 alert()

Use alert() An information dialog box pops up to the user , But this modal dialog just shows some information and a ‘ determine ’ Button . The term “ Modality ” It means that the script stops running temporarily , The interaction between the page and the user is also suspended , Until the user closes the dialog .

alert() Method takes a string as an argument :

alert('This is my message');
//alert() no return value

2.1.2 confirm()

confirm() A modal dialog box also pops up , It's like some information to the user . The difference is ,confirm() The dialog box provides the user with a choice , You can click on the “ determine ” or “ Cancel ” Button .

Clicking any button will close the dialog box , Let the script continue , But depending on which button was clicked ,confirm() Will return different Boolean values .

var answer = confirm("Are you happy to continue?");
// Return to answer A Boolean value ,True or False

2.1.3 prompt()

prompt It's another way to open modal dialog , It allows users to enter information .

var answer = prompt("What is your full name?");
var answer = prompt("What is your full name?","John Doe");
//prompt() Methods can also have a second optional parameter , Represents the default input , So that users don't click “ determine ” Button without entering any information .

prompt() The return value of the dialog depends on what the user has done

. If the user enters information , And then click “ determine ” or “ enter ” The return value is the string entered by the user

. If the user doesn't enter information, click “ determine ” or “ enter ”, The return value is to call prompt Method to set the default value

. If the user simply closes the dialog ( Click on “ Cancel ” or “ESC”), The return value is null

2.2 according to id Select element

2.2.1 getElementById()

If you want to go from HTML Select a specific page id The elements of , We just need to put the id Called as an argument document Object's getElementById() Method , It will return a specific value id Page elements corresponding to DOM object .

<div id='div1'>
...DIV Content of element ...
var myDiv = document.getElementById("div1");

2.2.2 innerHTML attribute

innerHTML Attributes for many DOM Object is a very useful property , You can read or set the... Inside a specific page element HTML Content .

hypothesis HTML The page contains the following elements :

<div id="div1">
<p>Here is some original text.</p>

utilize getElementById() and innerHTML() You can access this <div> The content of the element

var myDivContents = document.getElementById("div1").innerHTML

Variable myDivContents Contains the following characters :“<p>Here is some original text.</p>”

It can also be used innerHTML Set the content of the selected element :

 document.getElementById("div1").innerHTML = "<p>Here is some new text instead!</p>";

Executing the above code will delete <div> The element's current HTML Content , Replace... With a new string .

2.3 Access browser history

stay JavaScript in , Browser history is based on window.history The object represents , It's basically visited URL list . The method of this object allows us to use this list , But you can't modify these directly URL.

This object has only one property , That's the length of it (length), Represents the number of pages the user has visited :

alert("You 've visited" + history.length + "web pages in this brower sessions");

history There are three ways to object :

1.forward()  It's equivalent to clicking on the browser's “ Forward ” Button , You can get the next page in the history list

2.backward()   It's equivalent to clicking on the browser's “ back off ” Button , You can get the previous page in the history list

3.go()  It has a parameter , Is a positive or negative integer , You can jump to the relative position in the history list

history.go(-3); // Back off 3 A page 
history.go(2); // Forward 2 A page

This method can also take strings as parameters , Find the first match in the history list URL.

history.go("example.com"); // The first one in the history list contains "example.com" Of URL.

2.4 Use location object

2.4.1 location Object contains... Of the currently loaded page URL Information .

Page URL It's made up of many parts :

【 agreement 】//【 Host name 】:【 port 】/【 route 】【 Search for 】【hash】

Example :http://www.example.com:8080/tools/disiplay.php?section=435#list

1.location.href             "http://www.example.com:8080/tools/disiplay.php?section=435#list"

2.location.protocol       "http:"

3.location.host             "www.example.com:8080"

4.location.hostname    "www.example.com"

5location.port               "8080"

6.location.pathname    "/tools/disiplay.php"

7.location.search         "section=435"

8.location.hash            "#list"

2.4.2  Use location Object navigation

utilize location Object has two ways to help users navigate to a new page

The first is to set objects directly href attribute :

location.href = 'www.newpage.com';
// When using this method to move users to a new page , The original page remains in the browser's history , Users can use the browser's “ back off ” Button to return to the current page .

The second is to use new URL Replace the current page directly , Delete the current page from the history , have access to location Object's replace() Method :


2.4.3  Refresh the page

If you want to reload it in the browser ( Refresh ) Current page , have access to reload() Method :

// If you use... Without parameters reload() Method , When the current page is saved in the browser's cache , Will load the contents of the cache . To avoid that , Make sure you get the page data from the server , You can call reload() Method true

2.5  Browser information :navigator object

navigator Object contains the data of the browser program itself .

utilize navigator Object display information :

<!DOCTYPE html>
td{border:1px solid gray; padding:3px 5px;}
document.write("<tr><td>No of Plugins</td><td>"+navigator.plugins.length+"</td></tr>");

navigator Objects show us a rich history and a corner of complex industry competition . This information about user platforms is unreliable , But it's also the best it can offer .

Although browser compatibility is much better than in previous years , But sometimes we still need to understand the functions of the user's browser , And then use navigator Object is almost a wrong choice .

# Later on “ Function detection ”, It's a more accurate cross browser approach to detect the functionality of a user's browser , So as to decide how to carry out the corresponding operation .

2.6  Date and time

Date Object is used to process date and time .

2.6.1  Create... With the current date and time Date object

var mydate = new Date();
// Variable mydate It's just one. Date object , Contains the date and time information when the object was created

JavaScript There are many ways to get 、 Settings and editing Date Data in the object , Here are some examples :

var year = mydate.getFullYear(); // Four digit year , such as 2012
var month = mydate.getMonth(); // The number of months ,0-11,0 surface 1 month
var date = mydate.getDate(); // date ,1-31
var day = mydate.getDay(); // week ,0-6,0 Means Sunday
var hours = mydate.getHours(); // when ,0-23
var minutes = mydate.getMinutes(); // branch ,0-59
var seconds = mydate.getSeconds(); // second ,0-59

2.6.2  Create... With the specified date and time Date object

to Date() Statement passing the corresponding parameters , We can create any given date and time Date object , There are several ways : A little

There are many ways to operate the date and time , There will be Date The latest complete list of methods .

2.7  utilize Math Objects simplify operations

When you need to do all kinds of common operations , Use Math Objects can simplify a lot of work .

And Date Things with different objects ,Math Objects don't need to be created to use , You can call its methods directly .

2.7.1  integer

ceil(n) , floor() and round() Method to truncate the value with decimal point into integer in different ways :

var myNum1 = 12.55;
var myNum2 = 12.45;
alert(Math.floor(myNum1)); // Return rounding down to the nearest integer . Show 12
alert(Math.ceil(myNum1)); // Returns the integer rounded up to the nearest integer . Show 13
alert(Math.round(myNum1)); // Returns the number rounded to the nearest integer . Show 13
alert(Math.round(myNum2));// Show 12

2.7.2  Get the maximum and minimum

utilize max() and min() Minimum and maximum values can be obtained from a set of data :

var ageDavid = 23;
var ageMary = 27;
var ageChirs = 31;
var ageSandy = 19;
document.write("The youngest person is "+Math.min(ageDavid,ageMary,ageChirs,ageSandy)+"years old<br/>");
document.write("The oldest person is "+Math.max(ageDavid,ageMary,ageChirs,ageSandy)+"years old<br/>"); // Output results The youngest person is 19 yesrs old The oldest person is 31 years old

2.7.3 random number

utilize Math.random() Method can generate 0 To 1 A random number between .

2.7.4  Mathematical constants

A lot of constants are represented by Math The way to travel by attributes

E : The base of natural logarithm , It's about 2.176

LN2:2 The natural logarithm of , It's about 0.693

LN10:10 The natural logarithm of , It's about 2.302

LOG2E: With 2 Bottom e The logarithmic , It's about 1.442

LOG10E: With 10 Bottom e The logarithmic , It's about 0.434

PI: PI , It's about 3.14159

SQRT1_2:2 The reciprocal of the square root of , It's about 0.707

SQRT2:2 The square root of , It's about 1.414

2.7.5  keyword with

Any object can use keywords with, however Math Objects are the most suitable for demonstration . adopt with, We can reduce some boring keyboard input work

var myRand = random();
var biggest = max(3,4,5);
var height = round(76.35);

《javascript Introduction to classics 》-day02 More articles about

  1. 《javascript Introduction to classics 》-day01

    <javascript Introduction to classics >-day01 1. understand JavaScript 01. Every time the browser loads and displays a page , Create an internal representation of the page and all its elements in memory ,, That is to say DOM. stay DOM in , ...

  2. 【 turn 】HTML, CSS and Javascript Introduction to debugging

    turn http://www.cnblogs.com/PurpleTide/archive/2011/11/25/2262269.html HTML, CSS and Javascript Introduction to debugging This article introduces some new ideas ...

  3. JavaScript Quick start ( Four )——JavaScript function

    Function declaration In the previous three function declarations ( See JavaScript Quick start ( Two )——JavaScript Variable ), Use Function Constructor declaration methods are rare , Let's not talk about .function func() { ...

  4. Section 119 ,JavaScript Introduction to events

    JavaScript Introduction to events Learning points : 1. Introduction to the incident 2. Inline model 3. Script model 4. Event handler JavaScript Events are created by accessing Web A series of operations caused by the user of the page , for example : The user clicks . When the user performs certain operations ...

  5. JavaScript Simple introduction ( Supplement )

    This article is a review of the previous article  JavaScript Simple introduction   Some details of . One . Global and local variables stay <script> The variables defined in the tag are global variables in the current page . namely  <script> Labels can be straight ...

  6. Javascript Introduction to closures ( translation )

    Preface blanket : This article uses effective javascript The code explains closures to programmers , Daniel and functional programmers, please ignore . translator : The article is written in 2006 year , But until the translation of 21 Hours ago, the author was perfecting this article , stay Stackov ...

  7. JavaScript Classical scope problem ( Reprint )

    subject var a = 10; function test(){ a = 100; console.log(a); console.log(this.a); var a; console.log(a); ...

  8. Javascript Introduction to ( One )

    The last one learned what is JavaScript Language and its functions and unique characteristics, etc , This article will introduce in detail JavaScript Some ways to get started . For beginners , because JavaScript It's embedded in HTML In the page , First create a ...

  9. JavaScript Basic introduction

    JavaScript Basic introduction   JavaScript The composition of JS It's made up of three parts , They are :ECMAScript.DOM.BOM. ECMAScript     Because Netscape was developed JavaScrip ...

Random recommendation

  1. solve adb.exe&#39; and can be executed.

    Baidu google What we talk about more is task manager kill fall adb Or restart adb server, But I don't have a task manager adb , Guess it's a program taking up adb port . So follow this idea to find . 5037 by adb Default port see ...

  2. php How to get mac Address ?

    How to use php obtain mac The address? ? As we all know mac An address is the only global identifier of a computer , So this is very practical , For example, to make a voting function , that mac Address is essential Of , If you just rely on ip It must be inaccurate to judge this by address , Too much water ...

  3. JS The beginning of learning -for set for Traversing a two-dimensional array

    <!doctype html><html><head><meta charset="utf-8"><title> Untitled article ...

  4. [ turn ]AFNetWorking Use notes

    Reprinted from :http://blog.sina.com.cn/s/blog_719d537e01017x82.html AFNetwork It's a lightweight network request api Class library . In order to NSURLConnection ...

  5. DirectDraw

    One .DirectDraw Interface DirectDraw The interface diagram is as follows : 1.IUnknown: all COM Objects must be derived from this basic interface 2.IDirectDraw: This is starting to use DirectDraw Must create a master ...

  6. java fingerprint identification + Google Image Recognition Technology

    http://www.icodeguru.com/3/2451.html http://valseonline.org/thread-124-1-1.html

  7. commons.fileupload Simple application

    Import package : commons-fileupload-1.3.1.jar commons-io-2.4.jar commons-fileupload Depend on commons-io,commons-io-2.4 have to ...

  8. java Introduction to multithreading in

    process : A process includes memory space allocated by the operating system , Contains one or more threads . A thread cannot exist independently , It has to be part of the process . A process runs all the time , Not until all non daemons have finished running . The advantage of multithreading is high efficiency , charge ...

  9. install vue-cli Scaffolding construction tool

    vue install 1.vue install : $ cnpm install vue 2. install vue-cli Scaffolding construction tool : # Global installation vue-cli $ cnpm install --global vue-cli ...

  10. css js compatibility

    js   compatibility 1. document.form.item The problem is : There is... In the code document.formName.item("itemName") Such a statement , Can't be in FF Down shipment ...