JS Foundation & Case

JS Foundation

What is JS

  • JS, the full name of JavaScript, is a literal script language. It is a dynamic type, weak type and object-based script language with built-in support types.
  • Comparison between JS language and Java language:
Operating environmentJVM virtual machineJS engine is a part of the browser
Cross platform operationCross platformCross platform
Language typeStrongly typed languageWeakly typed, dynamically typed language
Need to compileIt needs to be compiled. It is a compiled languageIt does not need to be compiled. It is an interpretive language
Case sensitiveCase sensitiveCase sensitive

Role of JS

Specifically, it has two functions:

  • JS code can operate the browser (BOM): URL jump, history switching, browser pop-up, etc
  • JS code can operate web pages (DOM): operate HTML tags, tag attributes, styles, text, etc

Note: JS is a runtime operation in the browser memory and will not modify the web page source code, so the web page will be restored after refreshing the page

Composition of JS

  • ECMAScript (core): it is the basic syntax specification of JS
  • BOM: Browser Object Model, which provides a method to interact with the browser
  • DOM: Document Object Model, which provides methods for operating web pages

JS introduction

Internal JS (embedded)
External JS (external)

  • Internal JS
    Add the < script > tag in html and write the js code in the tag body
//Write js code here
  • External JS
    Write the JS code in a separate JS file. The suffix of JS file is js
    Using < script > tags in HTML to import external js files
<script src="js Path to file"></script>


<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>js Introduction mode-external js</title>
    <!--Introduction of external my.js file-->
    <script src="../js/my.js"></script>


There may be problems during external introduction. Please see the following article
The external introduction of js does not take effect
Another solution is to write the code introduced into the file to the end of the body

Some common methods

Pop up warning box


console output


Output to page (label supported)



javascript is a weakly typed language. The variable type of javascript is determined by its value. You need to use the keyword 'var' or 'let' to define variables
int i = 10; var i = 10; Or I = 10;
String a = "ha ha"; let str = "ha ha"; Or str = "ha ha"; Or str = "haha"

be careful:
1.var or it can be omitted. It is recommended to keep it
2. The last semicolon can be omitted and is recommended to be retained
3. Define multiple variables at the same time, which can be separated by "," and share a 'var' keyword var c = 45,d=‘qwe’,f=‘68’;

data type

  1. Five raw data types
data typedescribeExamples
numbervalue type1, 2, 3, 3.14
booleanBoolean typetrue, false
stringString type"hello", 'hello'
objectobject typenew Date(), null
undefinedType not definedvar a;
  1. typeof operator

Function: used to judge the type of variable
Writing method: typeof (variable name) or typeof variable name

Difference between null and undefined:
null: object type. The data type is known, but the object is empty.
Undefined: an undefined type. You don't know what data type it is.

Convert string to numeric type
Global functions (Methods) are functions that can be used directly anywhere in JS without importing objects. Does not belong to any object

arithmetic operation

var x = 2;
var y = "3";
console.log(x*y)//6. Implicit conversion * / is OK+ Is a string link - cannot convert

==Compare values, = = = compare values and types

var i = 2;
var j = "2";
alert(i==j); // ==The comparison is only numeric, true
alert(i===j); // ===Compare values and types false


Function of js: in order to encapsulate the code, call the function directly where you want to use the code
js function declaration method:
1. Ordinary function (named function)
2. Anonymous function

Ordinary function: function function name (parameter name, parameter name...) {function body}. The function has no return value type and no parameter type

Define common functions

function Function name(parameter list ){
   Function body
  [return Return value;]

Call normal function

var result = Function name(Argument list);


    function total(a,b,c) {
        console.log("arguments Data in array:"+arguments.length)
        return a+b+c

    //Call function
    //var num = total(1,2,3);

  1. js function also has two characteristics: 1 The number of parameters during function declaration and the number of parameters passed in during function call can be inconsistent; Because there is an arguments array inside the function, which is used to store the passed in parameters
  2. js functions are not overloaded, and the function with the same name will overwrite the function with the same name
    function total(a,b) {
        return a+b

    var num = total(1,2,3);


Anonymous function

Anonymous functions, also known as callback functions, are similar to methods in functional interfaces in Java

function(parameter list ){
   Function body
  [return Return value;]

JS event

Event introduction

HTML events are "things" that happen on HTML elements. They are things that browsers or users do
Events are usually used in conjunction with functions, so that function execution can be driven by the events that occur.

Common events

attributeWhen did this event occur
onclickThe event handle called when the user clicks on an object.
ondblclickThe event handle that is invoked when the user double clicks an object.
onchangeThe content of the domain is changed.
onblurElement loses focus.
onfocusElement gets focus.
onloadA page or an image is loaded.
onsubmitThe confirm button is clicked; The form is submitted.
onkeydownA keyboard key is pressed.
onkeypressA keyboard key is pressed.
onkeyupA keyboard key is released.
onmousedownThe mouse button is pressed.
onmouseupThe mouse button is released.
onmouseoutMove the mouse away from an element.
omouseoverMove the mouse over an element.
onmousemoveThe mouse is moved.

Event binding

Ordinary function mode

To put it bluntly, set the properties of the label

<Label properties="js Code, calling function"></label>

Anonymous function mode

   Label object.Event properties = function(){
       //Execute a piece of code

Event usage

Important events

Click event
Demand: without clicking the button once, hello pops up

<input type="button" value="Button" onclick="fn1()">
<input type="button" value="Another button" id="btn">

       //Function to call when clicking
       function fn1() {
       alert("I was clicked...")
//Bind the click event to another button:
//1. First obtain the label according to the id
let btn = document.getElementById("btn");
//2. Set onclick attribute of btn (binding event)
//Bind named function
//btn.onclick = fn1
//Bind anonymous function
btn.onclick = function () {
   console.log("Another button was clicked")
  • Introduction to common events of JS:
    1. onclick
    2. ondblclick
    3. onmouseover
    4. onmouseout
    5. onfocus get focus
    6. onblur lost focus


Browser Object Model In order to facilitate the operation of the browser, JavaScript encapsulates the objects in the browser, so that developers can easily operate the objects in the browser.

Five objects in BOM

window: form object

alert()Displays a warning box with a message and a confirmation button
confirm()Displays a dialog box with a message and confirm and Cancel buttons
promptPop up input box
setInterval('function name () ', time)Calls a function or evaluates an expression for a specified period (in milliseconds)
'timeout(), function name (')Call the function or computing expression after the specified millisecond count.
clearInterval()Cancels the Interval() set by setInterval().
clearTimeout()Cancels the timeout set by the setTimeout() method.
  1. Warning box
  1. Confirmation box
let flag = confirm("Are you sure you want to delete?");
  1. Input box
let age = prompt("Please enter your age");
if (parseInt(age) >= 18) {
   alert("Can access")
}else {
   alert("Please visit later")

Timer is to execute a task at intervals

  1. setTimeout(), a timer that executes only once, is actually equivalent to a delayer
    The first parameter is the anonymous function to be executed, and the second parameter is the execution time
setTimeout(function () {
          document.write("hello world")
  1. setInterval(), timer for loop execution
    The first parameter is the anonymous function to be executed, and the second parameter is the interval time. The return value of the method is the timer id
let i = 0
var id = setInterval(function () {
   i ++
   document.write("Hello world<br/>")
   //We have another method, clearinterval (timer id), to clear the timer
   if (i == 5) {

navigator: browser navigation object

appNameReturns the name of the browser
appVersionReturns the platform and version information of the browser

Screen: screen object

widthReturns the resolution width of the display screen
heightReturns the resolution height of the display screen

history: historical object

back()Load the previous URL in the history list
forword()Load the next URL in the history list
go()Load a specific page in the history list

location: current path information

hostSets or returns the host name and the port number of the current URL
hrefSet or return the full URL
portSets or returns the port number of the current URL

location.href; Get path
location.href = "http://www.baidu.com "; set the path and jump to Baidu page


What is dom

DOM: Document Object Model. It is provided by js, which is used to access all the contents in the web page (tags, attributes, tag contents)

What is a dom tree
When a web page is loaded, the browser creates a DOM object for the page. DOM object model is a tree structure: all tags, attributes and text in the web page will be converted into node objects and organized into a tree structure according to the hierarchical structure.
The object encapsulated into the whole web page is called document
The object encapsulated by the tag is called Element
The object encapsulated by Attribute is called Attribute
The object encapsulated by Text is called Text

Everything is a node, everything is an object

Operation label

Get tag

methoddescribeReturn value
document.getElementById(id)Get tag by idElement object
document.getElementsByName(name)Get a batch of tags according to tag nameElement class array
document.getElementsByTagName(tagName)Obtain a batch of labels according to the label nameElement class array
document.getElementsByClassName(className)Get a batch of labels according to the class nameElement class array

Operation label

methoddescribeReturn value
document.createElement(tagName)create labelElement object
parentElement.appendChild(sonElement)Insert label
element.remove()delete a tap
  1. Get label
    document.getElementById("id") is obtained by id
    document.getElementsByTagName("tag name") is obtained from the tag name
    document.getElementsByClassName("class name") is obtained from the class name
  2. Operation node (label, text)
    document.createElement(tagName) creates a label Element object
    document.createTextNode("text") creates a text node
    parentElement.appendChild(sonElement) insert label
    element.remove() deletes the label

Operation label body


  • Get label body content: label object innerHTML
  • Set label body content: label object innerHTML = "new HTML code";
    innerHTML is an overlay setting, and the original tag body content will be overwritten;
    Tags that support tags can be inserted, and the set html code will take effect


<!DOCTYPE html>
<html lang="en">
   <meta charset="UTF-8">
   <title>Operation label body</title>
<input type="button" value="obtain d1 Label body content" onclick="getHtml()">
<input type="button" value="set up d1 Label body content" onclick="setHtml()">
<div id="d1">
   var d1 = document.getElementById("d1");
   function getHtml() {
       var html = d1.innerHTML;
   function setHtml() {
       d1.innerHTML = "<h1>ee</h1>";
  1. Summary
    Get the contents of the label (get the label together)
    Label object innerHTML;

Set the content of the label (① the previous content will be overwritten; ② the label is supported)
Tag object, innerHTML = "html string";

Operation properties

Each tag Element object provides methods to manipulate attributes

Method namedescribeparameter
getAttribute(attrName)Get property valueAttribute name
setAttribute(attrName, attrValue)Set attribute valueAttribute name, attribute value
removeAttribute(attrName)Delete attributeAttribute name
  • getAttribute(attrName) gets the attribute value
  • setAttribute(attrName, attrValue) sets the attribute value
  • Removeattribute (attribrname) deletes an attribute


Objective: when pressing and holding the display password button, the password in the password box will be displayed; When the key is released, the password is hidden

    <input type="password" id="pwd">
    <input type="button" value="Show password" onmousedown="showPassword()" onmouseup="hidePassword()">
        //1. Bind onmousedown event to button
        function showPassword() {
            //Display the password in the password box: change the type attribute of the password box to text

        //2. Bind onmouseup event to button
        function hidePassword() {
            //Set the type of the password box to password

            //Getattribute (attribute name), get the attribute value according to the attribute name
            var type = document.getElementById("pwd").getAttribute("type");

Case rotation chart

        <img src="../img/banner_1.jpg" id="tu" width="500px" height="130px">
        var srcList = ["../img/banner_1.jpg","../img/banner_2.jpg","../img/banner_3.jpg"]
        var i = 0
        //Realize the rotation chart and switch one picture every three seconds
        //1. How to execute a task every three seconds (timer)
        setInterval(function () {
            //Every scheduled task i++
            i ++
            //Consider that if i is 3, reset i to 0
            if (i == 3) {
                i = 0
            //2. How to switch pictures: set src attribute of img tag


Drop down box secondary linkage
Add the native place on the registration page, with the drop-down list of provinces on the left and the drop-down list of cities on the right The select on the right updates the data according to the changes on the left

    <select id="provinceSelect">
        <option value="0">Please select a province</option>
        <option value="1">Guangdong Province</option>
        <option value="2">Hunan Province</option>
        <option value="3">Hubei province</option>
    <select id="citySelect">
        <option>Please select a city</option>

        //Prepare data
        var cities = [
            ["Changsha","Yueyang","Changde","city in Hunan"],

        //2. Bind onchange event to the drop-down box of the province
        var provinceSelect = document.getElementById("provinceSelect");

        provinceSelect.onchange = function () {
            //2.1 get all cities in the currently selected province
            var value = provinceSelect.value;
            //City array of current province
            var items = cities[value];

            //2.2 traverse every city
            //Before traversing and adding, first clear all option s in the city drop-down box, and innerHTML overwrites the previous content
            document.getElementById("citySelect").innerHTML = "<option>Please select a city</option>"
                    var s = "";
                    for(var i = 0;i <items.length;i++){
                        s += "<option>"+items[i]+"</option>";
			document.getElementById("citySelect").innerHTML += s;
	            // for (var i = 0; i < items.length; i++) {
	            //     //Every city
	            //     var cityName = items[i];
	            //     //Create option
	            //     var optionElement = document.createElement("option");
	            //     //Set the city name in the option tag body
	            //     optionElement.innerHTML = cityName
	            //     //Add the option tag to the city drop-down box
	            //     document.getElementById("citySelect").appendChild(optionElement)
	            // }

Keywords: Javascript Front-end html

Added by godfrank on Sat, 05 Mar 2022 08:22:36 +0200