[JaveWeb Tutorial] (3) Web front-end basics: Getting started with JavaScript is no longer difficult: an article teaches you how to easily handle JavaScript basic objects (Array String JSON), BOM objects, and DOM object examples with detailed explanations

Insert image description here

1. JavaScript object

There are many objects in JavaScript, which can be mainly divided into the following three categories. We can open the W3school online learning document , go to the homepage, and find JavaScript under Browser Script in the left column, as shown in the figure below:

Insert image description here

Then enter the following interface and click on the reference book on the right

Insert image description here

Then enter the following page, which lists all objects in JavaScript

Insert image description here

It can be roughly divided into three categories:

The first category: basic objects, we mainly learn Array, JSON and String

Insert image description here

The second category: BOM objects, mainly several objects related to browsers

Insert image description here

The third category: DOM object. In JavaScript, each tag of html is encapsulated into an object.

Insert image description here

Let’s first learn about the Array object, a basic object type.

1.1 Basic objects

1.1.1 Array object

Syntax format

Array objects are used to define arrays. There are two commonly used syntax formats:

Way 1:

var 变量名 = new Array(元素列表); 

For example:

var arr = new Array(1,2,3,4); //1,2,3,4 是存储在数组中的数据(元素)

Way 2:

var 变量名 = [ 元素列表 ]; 

For example:

var arr = [1,2,3,4]; //1,2,3,4 是存储在数组中的数据(元素)

The array is defined, so how do we get the values ​​in the array? Just like in Java, you need to use index to get the value in the array. The syntax is as follows:

arr[索引] =;

Next, we create a file named 02. JS-Object-Array.html in VS Code, define the array according to the above syntax, and obtain the values ​​in the array through indexing.

<script>
    //定义数组
     var arr = new Array(1,2,3,4);
     var arr = [1,2,3,4];
	//获取数组中的值,索引从0开始计数
     console.log(arr[0]);
     console.log(arr[1]);
</script>

The effect observed in the browser console is as follows: output 1 and 2

Insert image description here

Features

Unlike Java, arrays in JavaScript are equivalent to collections in Java, and the length of the array can be changed. Moreover, JavaScript is a weak data type language, so values ​​of any data type can be stored in the array. Next we demonstrate the above features through code.

Comment out the previous code and add the following code:

//特点: 长度可变 类型可变
var arr = [1,2,3,4];
arr[10] = 50;

console.log(arr[10]);
console.log(arr[9]);
console.log(arr[8]);

In the arr variable defined in the above code, the length of the array is 4, but we directly add the data 10 at the position of index 10, and output the element at the position of index 10. The browser console data result is as follows:

Insert image description here

Because there are no values ​​at indexes 8 and 9, the output content is undefined. Of course, we can also add other types of values ​​to the array. Add the code as follows: Comment out the code output by the console before

//特点: 长度可变 类型可变
var arr = [1,2,3,4];
arr[10] = 50;

// console.log(arr[10]);
// console.log(arr[9]);
// console.log(arr[8]);

arr[9] = "A";
arr[8] = true;

console.log(arr);

The browser console output is as follows:

Insert image description here

Properties and methods

Array is an object, and the object has properties and methods, so next we introduce the properties and methods of the Array object.

The official documentation provides many properties and methods of Array, but we only learn the commonly used properties and methods, as shown in the following figure:

Attributes:

Attributes describe
length Sets or returns the number of elements in an array.

method:

method method describe
forEach() Iterates through each valuable element in the array and calls the passed function once
push() Adds a new element to the end of the array and returns the new length
splice() Remove elements from array
  • length attribute:

    The length attribute can be used to get the length of the array, so we can use this attribute to traverse the elements in the array and add the following code:

    var arr = [1,2,3,4];
    arr[10] = 50;
    	for (let i = 0; i < arr.length; i++) {
          
          
    	console.log(arr[i]);
    }
    

    The browser console output is as shown in the figure:

    Insert image description here

  • forEach() function

    First we learn the forEach() method. As the name suggests, it is used for traversal. So what does traversal do? Therefore, the parameters of this method need to pass a function, and this function accepts one parameter, which is the value of the array during traversal. The traversal code before modification is as follows:

    //e是形参,接受的是数组遍历时的值
    arr.forEach(function(e){
          
          
         console.log(e);
    })
    

    Of course, in ES6, the arrow function is introduced, and the syntax is similar to the lambda expression in Java. Modify the above code as follows:

    arr.forEach((e) => {
          
          
         console.log(e);
    }) 
    

    The browser output is as follows: Note that content without elements will not be output, because forEach will only traverse elements with values.

    Insert image description here

  • push() function

    The push() function is used to add elements to the end of the array. The parameters of the function are the elements that need to be added. Write the following code: add 3 elements to the end of the array.

    //push: 添加元素到数组末尾
    arr.push(7,8,9);
    console.log(arr);
    

    The browser output is as follows:

    Insert image description here

  • splice() function

    The splice() function is used to select elements in an array, and fill in 2 parameters in the function.

    Parameter 1: Indicates which index position to delete from

    Parameter 2: Indicates the number of deleted elements

    The following code indicates: start deleting from index 2 and delete 2 elements.

    //splice: 删除元素
    arr.splice(2,2);
    console.log(arr);
    

    The browser execution effect is as follows: elements 3 and 4 are deleted, element 3 is index 2

    Insert image description here

The complete code for the Array array is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS-对象-Array</title>
</head>
<body>
    
</body>
<script>
    //定义数组
    // var arr = new Array(1,2,3,4);
    // var arr = [1,2,3,4];

    // console.log(arr[0]);
    // console.log(arr[1]);

    //特点: 长度可变 类型可变
    // var arr = [1,2,3,4];
    // arr[10] = 50;

    // console.log(arr[10]);
    // console.log(arr[9]);
    // console.log(arr[8]);

    // arr[9] = "A";
    // arr[8] = true;

    // console.log(arr);



    var arr = [1,2,3,4];
    arr[10] = 50;
    // for (let i = 0; i < arr.length; i++) {
      
      
    //     console.log(arr[i]);
    // }

    // console.log("==================");

    //forEach: 遍历数组中有值的元素
    // arr.forEach(function(e){
      
      
    //     console.log(e);
    // })

    // //ES6 箭头函数: (...) => {...} -- 简化函数定义
    // arr.forEach((e) => {
      
      
    //     console.log(e);
    // }) 

    //push: 添加元素到数组末尾
    // arr.push(7,8,9);
    // console.log(arr);

    //splice: 删除元素
    arr.splice(2,2);
    console.log(arr);

</script>
</html>

1.1.2 String object

Syntax format

There are two ways to create String objects:

Way 1:

var 变量名 = new String("…") ; //方式一

For example:

var str = new String("Hello String");

Way 2:

var 变量名 = "…" ; //方式二

For example:

var str = 'Hello String';

According to the above format, create a file named 03. JS-Object-String.html in VS Code and write the code as follows:

<script>
    //创建字符串对象
    //var str = new String("Hello String");
    var str = "  Hello String    ";

    console.log(str);
</script>

The browser console output is as follows:

Insert image description here

Properties and methods

String objects also provide some commonly used properties and methods, as shown in the following table:

Attributes:

Attributes describe
length The length of the string.

method:

method describe
charAt() Returns the character at the specified position.
indexOf() Retrieve a string.
trim() Remove spaces from both sides of string
substring() Extracts characters between two specified index numbers in a string.
  • length attribute:

    The length attribute can be used to return the length of a string. Add the following code:

    //length
    console.log(str.length);
    
  • charAt() function:

    The charAt() function is used to return the character at the specified index position. The parameter of the function is the index. Add the following code:

    console.log(str.charAt(4));
    
  • indexOf() function

    The indexOf() function is used to retrieve the index position of the specified content in the string. The return value is the index and the parameter is the specified content. Add the following code:

    console.log(str.indexOf("lo"));
    
  • trim() function

    The trim() function is used to remove spaces on both sides of a string. Add the following code:

    var s = str.trim();
    console.log(s.length);
    
  • substring() function

    The substring() function is used to intercept strings. The function has 2 parameters.

    Parameter 1: Indicates the index position from which to intercept. Include

    Parameter 2: Indicates the index position to end at. Not included

    console.log(s.substring(0,5));
    

The overall code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS-对象-String</title>
</head>
<body>
    
</body>
<script>
    //创建字符串对象
    //var str = new String("Hello String");
    var str = "  Hello String    ";

    console.log(str);

    //length
    console.log(str.length);

    //charAt
    console.log(str.charAt(4));

    //indexOf
    console.log(str.indexOf("lo"));

    //trim
    var s = str.trim();
    console.log(s.length);

    //substring(start,end) --- 开始索引, 结束索引 (含头不含尾)
    console.log(s.substring(0,5));

</script>
</html>

The browser execution effect is shown in the figure:

Insert image description here

1.1.3 JSON object

custom object

Customizing objects in JavaScript is particularly simple, and its syntax is as follows:

var 对象名 = {
    
    
    属性名1: 属性值1, 
    属性名2: 属性值2,
    属性名3: 属性值3,
    函数名称: function(形参列表){
    
    }
};

We can call properties with the following syntax:

对象名.属性名

Call the function with the following syntax:

对象名.函数名()

Next, we create a file named 04. JS-Object-JSON.html in VS Code to demonstrate the custom object

<script>
    //自定义对象
    var user = {
        name: "Tom",
        age: 10,
        gender: "male",
        eat: function(){
             console.log("用膳~");
         }
    }

    console.log(user.name);
    user.eat();
<script>

The browser console results are as follows:

Insert image description here

The syntax of the above function definition can be simplified into the following format:

    var user = {
    
    
        name: "Tom",
        age: 10,
        gender: "male",
        // eat: function(){
    
    
        //      console.log("用膳~");
        //  }
        eat(){
    
    
            console.log("用膳~");
        }
    }
json object

JSON object: J ava Script Object Notation , JavaScript object notation . Is text written using JavaScript notation. Its format is as follows:

{
    
    
    "key":value,
    "key":value,
    "key":value
}

Among them, the key must be quoted and marked with double quotes, and the value can be any data type.

For example, we can directly search "json online parsing" on Baidu, choose one to enter, and then write the following content:

{
    
    
	"name": "李传播"
}

Insert image description here

But when we switch the double quotes to single quotes and verify again, an error is reported, as shown in the following figure:

Insert image description here

So where is text in data format like json used in enterprise development? -- Often used as a data carrier for front-end and back-end interactions

As shown in the figure below: During front-end and back-end interaction, we need to transmit data, but how do we describe objects in Java? We can use the xml format as shown in the figure to clearly describe the java objects in java that need to be passed to the front end.

Insert image description here

However, the xml format has the following problems:

  • Labels need to be written in duplicate, which takes up bandwidth and wastes resources.
  • The analysis is cumbersome

So we can use json instead, as shown in the figure below:

Insert image description here

Next, we demonstrate the json object through code: comment out the previous code and write the code as follows:

var jsonstr = '{"name":"Tom", "age":18, "addr":["北京","上海","西安"]}';
alert(jsonstr.name);

The browser output is as follows:

Insert image description here

why? **Because the above is a json string, not a json object, we need to use the following functions to convert json strings and json objects. **Add the code as follows:

var obj = JSON.parse(jsonstr);
alert(obj.name);

At this time, the browser output is as follows:

Insert image description here

Of course, we can also convert the json object into a json string again through the following function. Add the following code:

alert(JSON.stringify(obj));

The browser output is as shown in the figure:

Insert image description here

The overall code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS-对象-JSON</title>
</head>
<body>
    
</body>
<script>
    //自定义对象
    // var user = {
      
      
    //     name: "Tom",
    //     age: 10,
    //     gender: "male",
    //     // eat: function(){
      
      
    //     //      console.log("用膳~");
    //     //  }
    //     eat(){
      
      
    //         console.log("用膳~");
    //     }
    // }

    // console.log(user.name);
    // user.eat();


    // //定义json
    var jsonstr = '{"name":"Tom", "age":18, "addr":["北京","上海","西安"]}';
    //alert(jsonstr.name);

    // //json字符串--js对象
    var obj = JSON.parse(jsonstr);
    //alert(obj.name);

    // //js对象--json字符串
    alert(JSON.stringify(obj));


</script>
</html>

1.2 BOM object

Next we learn the BOM object. The full name of BOM is Browser Object Model, which translates to browser object model. That is, JavaScript encapsulates various components of the browser into objects. If we want to operate some functions of the browser, we can do so by operating the relevant properties or functions of the BOM object. For example: if we want to change the browser's address to http://www.baidu.com, we can do it through the href attribute of the location object provided in the BOM. The code is as follows:location.href='http://www.baidu.com'

The following 5 objects are provided in the BOM:

object name describe
Window browser window object
Navigator browser object
Screen screen object
History history object
Location daddress bar object

The relationship between the above five objects and each component of the browser is as shown in the figure below:

Insert image description here

For the above five objects, we focus on the Window object and the Location object.

1.2.1 Window object

The window object refers to the browser window object, which is all JavaScript objects, so we can use the window object directly, and for the methods and properties of the window object, we can omit window. For example: the alert() function we learned before In fact, it belongs to the window object. Its complete code is as follows:

window.alert('hello');

It can omit window. So it can be abbreviated as

alert('hello')

Therefore, we use abbreviations for the properties and methods of the window object. Window provides many properties and methods. The following table lists the commonly used properties and methods.

The window object provides properties for obtaining other BOM objects:

Attributes describe
history Used to obtain the history object
location Used to obtain the location object
Navigator Used to obtain Navigator object
Screen Used to obtain Screen object

That is to say, if we want to use the location object, we only need to use it through code window.locationor abbreviation.location

Window also provides some commonly used functions, as shown in the following table:

function describe
alert() Displays an alert box with a message and a confirm button.
confirm() Displays a dialog box with a message and confirm and cancel buttons.
setInterval() Calls a function or evaluates an expression at a specified period in milliseconds.
setTimeout() Calls a function or calculated expression after a specified number of milliseconds.

Next, we write code to demonstrate the above function by creating a file named 05. JS-Object-BOM.html in VS Code:

  • alert() function: pops up a warning box, the content of the function is the content of the warning box

    <script>
        //window对象是全局对象,window对象的属性和方法在调用时可以省略window.
        window.alert("Hello BOM");
        alert("Hello BOM Window");
    </script>
    

    Open the browser and pop up the boxes one by one. Here is only one screenshot.

    Insert image description here

  • confirm() function: pops up a confirmation box and provides the user with 2 buttons, namely confirm and cancel.

    Add the following code:

    confirm("您确认删除该记录吗?");
    

    The browser opening effect is as shown in the figure:

    Insert image description here

    But how do we know if the user clicked Confirm or Cancel? So this function has a return value. When the user clicks confirm, it returns true, and when the user clicks cancel, it returns false. We decide whether to perform subsequent operations based on the return value. Modify the code as follows: run it again and you can view the return value true or false.

    var flag = confirm("您确认删除该记录吗?");
    alert(flag);
    
  • setInterval(fn, millisecond value): timer, used to execute a certain function periodically and in a loop . This function needs to pass 2 parameters:

    fn: function, function code that needs to be executed periodically

    Millisecond value: interval time

    Comment out the previous code and add the following code:

    //定时器 - setInterval -- 周期性的执行某一个函数
    var i = 0;
    setInterval(function(){
          
          
         i++;
         console.log("定时器执行了"+i+"次");
    },2000);
    

    Refresh the page, and the browser will output on the console every period of time. The results are as follows:

    Insert image description here

  • setTimeout(fn, millisecond value): timer, which will only execute the function once after a period of time . The parameters are consistent with the above setInterval

    Comment out the previous code and add the following code:

    //定时器 - setTimeout -- 延迟指定时间执行一次 
    setTimeout(function(){
          
          
    	alert("JS");
    },3000);
    

    When the browser is opened, a pop-up box pops up after 3 seconds. When I close the pop-up box, I find that the pop-up box no longer pops up.

1.2.2 Location object

Location refers to the browser's address bar object. For this object, we commonly use the href attribute, which is used to obtain or set the browser's address information. Add the following code:

//获取浏览器地址栏信息
alert(location.href);
//设置浏览器地址栏信息
location.href = "https://www.itcast.cn";

The browser effect is as follows: First, a pop-up box displays the browser address bar information.

Insert image description here

Then click OK. Because we set the address bar information, the browser jumps to Chuanzhi homepage.

The complete code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS-对象-BOM</title>
</head>
<body>
    
</body>
<script>
    //获取
    // window.alert("Hello BOM");
    // alert("Hello BOM Window");

    //方法
    //confirm - 对话框 -- 确认: true , 取消: false
    // var flag = confirm("您确认删除该记录吗?");
    // alert(flag);

    //定时器 - setInterval -- 周期性的执行某一个函数
    // var i = 0;
    // setInterval(function(){
      
      
    //     i++;
    //     console.log("定时器执行了"+i+"次");
    // },2000);

    //定时器 - setTimeout -- 延迟指定时间执行一次 
    // setTimeout(function(){
      
      
    //     alert("JS");
    // },3000);
    
    //location
    alert(location.href);

    location.href = "https://www.itcast.cn";

</script>
</html>

1.3 DOM objects

1.3.1 Introduction to DOM

DOM: Document Object Model. That is, JavaScript encapsulates each component of the HTML document into objects.

In fact, we are not unfamiliar with DOM. We have come into contact with it before when learning XML. However, the tags in XML documents require us to write code to parse, while HTML documents are parsed by the browser. The encapsulated objects are divided into

  • Document: the entire document object
  • Element: element object
  • Attribute: attribute object
  • Text: text object
  • Comment: comment object

As shown below, the left side is the HTML document content, and the right side is the DOM tree.

Insert image description here

So what is the use of learning DOM technology? The main functions are as follows:

  • Change the content of HTML elements
  • Changing the style of HTML elements (CSS)
  • React to HTML DOM events
  • Add and remove HTML elements

In short, the purpose of dynamically changing the page effect is achieved. Specifically, we can view the 06. JS-Object-DOM-Demo.html provided in the code to experience the effect of DOM.

1.3.2 Get DOM object

We know that the role of DOM is to achieve various dynamic effects on the page by modifying the content and style of HTML elements, but the prerequisite for us to operate DOM objects is to obtain the element objects first and then operate. Therefore, the main core of learning DOM is to learn the following two points:

  • How to get the element object in the DOM (Element object, that is, label)
  • How to operate the properties of the Element object, that is, the properties of the label.

Next, let's first learn how to get the element object in the DOM.

The Element object in HTML can be obtained through the Document object, and the Document object is obtained through the window object. The API provided by the document object for obtaining the Element element object is shown in the following table:

function describe
document.getElementById() Get based on the id attribute value and return a single Element object
document.getElementsByTagName() Get based on the tag name and return an array of Element objects
document.getElementsByName() Obtain according to the name attribute value and return an array of Element objects
document.getElementsByClassName() Obtain according to the class attribute value and return an array of Element objects

Next, we create a file named 07. JS-Object-DOM-Get Elements.html in VS Code to demonstrate the above api. First, prepare the following page code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS-对象-DOM</title>
</head>

<body>
    <img id="h1" src="img/off.gif">  <br><br>

    <div class="cls">传智教育</div>   <br>
    <div class="cls">黑马程序员</div>  <br>

    <input type="checkbox" name="hobby"> 电影
    <input type="checkbox" name="hobby"> 旅游
    <input type="checkbox" name="hobby"> 游戏
</body>

</html>
  • document.getElementById(): Obtain the label object according to the id attribute of the label. The id is unique, so a single label object is obtained.

    Add the following code:

    <script>
    //1. 获取Element元素
    
    //1.1 获取元素-根据ID获取
     var img = document.getElementById('h1');
     alert(img);
    </script>
    

    The browser is opened, and the effect is as shown in the figure: It can be seen from the pop-up result that this is an image tag object

    Insert image description here

  • document.getElementsByTagName(): Get the tag object based on the name of the tag. There are many tags with the same name, so the return value is an array.

    Add the following code:

    //1.2 获取元素-根据标签获取 - div
    var divs = document.getElementsByTagName('div');
    for (let i = 0; i < divs.length; i++) {
          
          
         alert(divs[i]);
    }
    

    The browser outputs the pop-up box shown below twice.

    Insert image description here

  • document.getElementsByName(): Get the label object based on the name attribute value of the label. The name attribute value can be repeated, so the return value is an array.

    Add the following code:

    //1.3 获取元素-根据name属性获取
    var ins = document.getElementsByName('hobby');
    for (let i = 0; i < ins.length; i++) {
          
          
        alert(ins[i]);
    }
    

    The browser will pop up three times as shown below:

    Insert image description here

  • document.getElementsByClassName(): Get the label object based on the class attribute value of the label. The class attribute value can also be repeated. The return value is an array.

    Add code as shown below:

    //1.4 获取元素-根据class属性获取
    var divs = document.getElementsByClassName('cls');
    for (let i = 0; i < divs.length; i++) {
          
          
         alert(divs[i]);
    }
    

    The browser will pop up twice, both of which are div tag objects.

    Insert image description here

  • Operational properties

    So after getting the tag, how do we operate the tag's attributes? By querying the document information, as shown in the figure below:

    Insert image description here

    It follows that we can modify the content of the tag through the innerHTML attribute of the div tag object. At this time, we want to replace Chuanzhi Education in the page with Chuanzhi Education 666 , so we need to get the first of the two divs, so we can get the first div in the array through subscript 0, and comment on the previous code, Write the following code:

    var divs = document.getElementsByClassName('cls');
    var div1 = divs[0];
    
    div1.innerHTML = "传智教育666";
    

    The browser refreshes the page, and the display effect is as shown below:

    Insert image description here

    I found that the content of the page changed to Chuanzhi Education 666

The complete code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS-对象-DOM</title>
</head>

<body>
    <img id="h1" src="img/off.gif">  <br><br>

    <div class="cls">传智教育</div>   <br>
    <div class="cls">黑马程序员</div>  <br>

    <input type="checkbox" name="hobby"> 电影
    <input type="checkbox" name="hobby"> 旅游
    <input type="checkbox" name="hobby"> 游戏
</body>

<script>
    //1. 获取Element元素

    //1.1 获取元素-根据ID获取
    // var img = document.getElementById('h1');
    // alert(img);

    //1.2 获取元素-根据标签获取 - div
    // var divs = document.getElementsByTagName('div');
    // for (let i = 0; i < divs.length; i++) {
      
      
    //     alert(divs[i]);
    // }


    //1.3 获取元素-根据name属性获取
    // var ins = document.getElementsByName('hobby');
    // for (let i = 0; i < ins.length; i++) {
      
      
    //     alert(ins[i]);
    // }


    //1.4 获取元素-根据class属性获取
    // var divs = document.getElementsByClassName('cls');
    // for (let i = 0; i < divs.length; i++) {
      
      
    //     alert(divs[i]);
    // }



    //2. 查询参考手册, 属性、方法
    var divs = document.getElementsByClassName('cls');
    var div1 = divs[0];
    
    div1.innerHTML = "传智教育666";

</script>
</html>

1.4 Case

1.4.1 Requirements Description

Lu Xun said it well, just talk without practicing fake moves, just practice without talking about silly moves. So next we need to use cases to strengthen our mastery of the above DOM knowledge. There are three requirements:

  • light bulb
  • Add: very good after the tag body content of all div tags
  • Make all checkboxes appear selected

The effect is as follows:

Insert image description here

1.4.2 Data preparation

Create an img file in the JS directory, which is the same level used to store html files, and then 资料/图片素材copy the two pictures provided in to the img folder. The final overall result is as shown below:

Insert image description here

Create a file named 08.JS-Object-DOM-Case.html in VS Code, and then prepare the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS-对象-DOM-案例</title>
</head>

<body>
    <img id="h1" src="img/off.gif">  <br><br>

    <div class="cls">传智教育</div>   <br>
    <div class="cls">黑马程序员</div>  <br>

    <input type="checkbox" name="hobby"> 电影
    <input type="checkbox" name="hobby"> 旅游
    <input type="checkbox" name="hobby"> 游戏
</body>

<script>
  
</script>
</html>

The effect when the browser is opened is as shown in the figure:

Insert image description here

1.4.3 Requirement 1

  • need

    light bulb

  • analyze

    At this point we need to turn on the light bulb, which is actually changing the picture. Then if we need to switch pictures, we need to operate the src attribute of the picture. To operate the src attribute of the image, you need to first obtain the img tag object.

  • step

    • First get the img tag object
    • Then modify the src attribute value of the img tag object to switch images.
  • Code

    //1. 点亮灯泡 : src 属性值
    //首先获取img标签对象
    var img = document.getElementById('h1');
    //然后修改img标签对象的src属性值,进行图片的切换
    img.src = "img/on.gif";
    

The browser opens, and the effect is as shown in the figure:

Insert image description here

1.4.4 Requirement 2

  • need

    Add: very good after the tag body content of all div tags

    And very good is in red font

  • analyze

    We need to append the red "very good" after the original content. So we first need to obtain the original content, and then append the content. But how to ensure that very good is red? So we can complete it through the <font> tag and attributes we learned before in HTML. How to replace content? We learned about the innerHTML attribute before. The contents of two divs need to be replaced, so we need to obtain the two divs and traverse them to replace them.

  • step

    • Get all div tags by the tag's name div
    • Traverse all div tags
    • Get the original content of the div tag, then append <font color='red'>very good</font> and replace the original content
  • Code

    //2. 将所有div标签的内容后面加上: very good (红色字体) -- <font color='red'></font>
    var divs = document.getElementsByTagName('div');
    for (let i = 0; i < divs.length; i++) {
          
          
        const div = divs[i];
        div.innerHTML += "<font color='red'>very good</font>"; 
    }
    

The browser opening effect is as shown in the figure:

Insert image description here

1.4.5 Requirement 3

  • need

    Make all checkboxes appear selected

  • analyze

    To make the check box selected, what properties or methods can make the check box selected? You can query the data and find that the checked attribute of the checkbox label object is set to true, and you can change the checkbox to the selected state. Then we need to set all checkboxes, then we need to get all checkboxes and traverse

  • step

    • All checkbox tags can be obtained through the name attribute value
    • Traverse all checkbox tags,
    • Set each checkbox label
  • Code

    // //3. 使所有的复选框呈现选中状态
    var ins = document.getElementsByName('hobby');
    for (let i = 0; i < ins.length; i++) {
          
          
    const check = ins[i];
    check.checked = true;//选中
    }
    

Refresh the browser and the effect is as shown in the figure:

Insert image description here

1.4.6 Complete code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS-对象-DOM-案例</title>
</head>

<body>
    <img id="h1" src="img/off.gif">  <br><br>

    <div class="cls">传智教育</div>   <br>
    <div class="cls">黑马程序员</div>  <br>

    <input type="checkbox" name="hobby"> 电影
    <input type="checkbox" name="hobby"> 旅游
    <input type="checkbox" name="hobby"> 游戏
</body>

<script>
    //1. 点亮灯泡 : src 属性值
    var img = document.getElementById('h1');
    img.src = "img/on.gif";


    //2. 将所有div标签的内容后面加上: very good (红色字体) -- <font color='red'></font>
    var divs = document.getElementsByTagName('div');
    for (let i = 0; i < divs.length; i++) {
      
      
        const div = divs[i];
        div.innerHTML += "<font color='red'>very good</font>"; 
    }


    // //3. 使所有的复选框呈现选中状态
    var ins = document.getElementsByName('hobby');
    for (let i = 0; i < ins.length; i++) {
      
      
        const check = ins[i];
        check.checked = true;//选中
    }

</script>
</html>

Guess you like

Origin blog.csdn.net/shenchengyv/article/details/135419786