web front piece: JavaScript Basics (white on understand deft) -2

A Recap:

ECMAScript basic grammar

1. The basic data types and the reference data type

基本数据类型number,string,boolean,undefined,null
引用数据类型:Array,Object,Function

2. Analyzing and cycle conditions

switch(name){
    case 'xxx';
        break;
    case 'xxx';
        break;
    default:
        break;
}

for (var i=0;i<10;i++){
    run to code
}
三元运算:
1>3? '真的':'假的';

3. assignment operators, Logical Operators

&& || !
i ++
==比较值 ===比较值和数据类型

4. Common string

slice() 切片 一个参数从当前位置切到最后,两个参数顾头不顾尾
substring()
substr()  如果有两个参数,第二个参数表示切字符串的个数
join()

字符串拼接
concat()
+
es6的模版字符串
    ··插入变量用${变量名}

//获取索引
indexOf()
lastIndexOf()
//获取字符
charAt()
//获取字符ascii码
charCodeAt()

//转大写
toUppercase()
//转小写
tolowercase()

typeOf 校验当前变量的数据类型
trim 清除左右的空格

5. The method of array common

toString()
join('#')
concat()
//栈
push()
pop()
//堆
unshift()
shift()

splice(起始位置,删除的个数,添加的元素);
//增加,删除,替换
reverse()
sort()
slice()
length

//迭代方法
forEach() //仅能在数组对象中使用。
for
    
在函数中arguments  这个对象是伪数组

6. Object

function fn(name){
    var obj = {};
    obj[name]='mjj';
    return obj;
}
fn('age')
//遍历对象
for (var key in obj) {
    obj[key]
}

7. Functions

1.创建方法
//普通函数
function fn(){

}
fn();
//函数表达式
var fn = function(){
    run to code
}
//匿名函数
(function(){})()//this指向一定指向window

全局作用域,函数作用域,函数作用域中this指向可以发生改变,可以使用call() 或者apply()
e.g.:
var obj = {name:'mjj'};
function fn(){
    console.log(this.name);
}
fn();//是空制,因为函数内容this指向window
fn.call(obj);//此时函数内部的this指向obj


构造函数
new object();
new Array();
new String();


父级定义一个属性必须使用prototype

8. Date Object

var data = new Data();

date.toLocaleString()  //2018/08/21 21:33:23

9.Math mathematical objects

Math.ceil(); 向上取整,天花板函数
Math.floor(); 向下取整,地板函数
Math.round(); 标准的四舍五入

随机数
Math.random();获取到0-1之间的数

function random(min,max){
    Math.floor(Math.random()*(max-min))+min;
}

10. numeric and string conversion

1.数值转字符串
toString()
数字+空字符串
2.字符串转数值
parseInt() 转整数
parseFloat() 转浮点型
Number()

NAN
isNaN()

Infinity 无限大

11.let var difference

1.ES6可以用let定义块级作用域变量
2.let 配合for循环的独特应用
3.let没有变量提升与暂时性死区
4.let变量不能重复声明

12. A look at the code written results

var a = 99;            // 全局变量a
f();                   // f是函数,虽然定义在调用的后面,但是函数声明会提升到作用域的顶部。 
console.log(a);        // a=>99,  此时是全局变量的a
function f() {
  console.log(a);      // 当前的a变量是下面变量a声明提升后,默认值undefined
  var a = 10;
  console.log(a);      // a => 10
}
//undefined
//10
//99

II. Details:

1.BOM (Browser Object Model)

  • BOM is the core object Window, it represents an instance of the browser, in the browser, window object has a dual role, that is, JavaScript access to a browser window interface.

    ECMAScript is defined Global object.

1. System dialog box method

1.alert () warning box
<body>
    <script type="text/javascript">
        window.alert('mjj');
    </script>
</body>
  • Results show:

  • example

    //例题:
    <script>
        console.log(window.location);
        var i=1;
        function f(){
            i++;
            console.log("打印 :  "+i);
            return k;
            function k() {
                return "I love you!"
            }
        }
        f();
        console.log("111111111111");
        f()();
        alert(f()());
    </script>
    //打印2
    //11111111111
    //打印3
    //打印4
    //警告框出现"I love you!"
2.confirm () check box
  • If you click OK to return true, click Cancel to return false.
<body>
    <script type="text/javascript">
        var src = window.prompt("今天天气如何");
        switch (src) {
            case '晴天':
                console.log('出去打球');
                break;
            case '阴天':
                console.log('在家睡觉');
                break;
            default:
                console.log("什么都不做");
                break
        }
    </script>
</body>
  • Results show:

3.prompt () pop-up box
  • The default prompt accepts two parameters, a first parameter display text, a second parameter default text.
<body>
    <script type="text/javascript">
        var src = window.prompt("今天天气如何",'晴天');
        switch (src) {
            case '晴天':
                console.log('出去打球');
                break;
            case '阴天':
                console.log('在家睡觉');
                break;
            default:
                console.log("什么都不做");
                break
        }
    </script>
</body>
  • Results show

2. Timing Method **********

1. one-time task setTimeout ()
  • setTimeout () method represents a disposable timer task to do something, it receives two parameters, the first parameter is a function performed by the second parameter is the time (in milliseconds Timing: 1000 ms == 1 second)
    <script type="text/javascript">
        window.setTimeout(function(){
            console.log('2秒后我将打印');
        },2000);
        console.log('立刻打印');
    </script>
//setTimeout(参数1,参数2);参数1为一个函数,参数2为时间以毫秒为单位。此处要知道setTimeout是异步。

  • A one-time task of clearing

    var timer = setTimeout(callback,1000);
    clearTimeout(timer);
    //清除定时器。
  • href attribute

    //2秒后跳转 百度网页
    setTimeout(function () {
      location.href = 'https://www.baidu.com';
    },2000);
  • replace

    //2秒后跳转 百度网页,在当前页面跳转
    setTimeout(function(){
        location.replace('https://www.baidu.com');
    },2000)
2. periodic cycle setInterval
  • setInterval()The method represents a periodic cycle timer task which the received parameter with setTimeout()a method the same.

<script>
    var num = 0;
    var timer = null;
    //开启定时器
    timer = window.setInterval(function(){
        num++;
        if (num===10){
            //当num===10  清除定时器
            clearInterval(timer);
        }
        console.log(num);//console打印出数字
    },1000);//1000ms=1s
</script>
//每2秒刷新。
setInterval(function(){
    //做测试
    location.reload();
},2000);

//局部刷新  ajax技术,在不重载页面上,对网页进行操作
3.locaion object properties
  • location is one of the most useful of the BOM object that provides information about the document is loaded with the current window also provides some navigation functions. In fact, location is very special objects of an object, because it is a property of the window object, but also the document object's properties;
    <script>
        console.log(window.location);//获取属性
        setInterval(function(){
            location.reload();//刷新页面
        },2000);
    </script>
//局限较大,通常都是局部刷新,通过AJAX技术,在不重载页面的情况,对网页进行操作
  • reload () method

    location.reload();//重新加载(有可能从缓存中加载)
    location.reload(true;)//重新加载(强制从服务器加载)
  • history

    history.go(-1);//后退一页
    history.go(1);//前进一页
    history.go(2);//前进两页
console.log(window.location);
//获取属性
  • display effect

2.DOM (Document Object Model)

  • Top-level object BOM ----> Documents ------> Document Content

2.1 Node

  • Element node
    • Like <body>, <p>, <ul>elements like those we are called called element node (element node).
  • Text node
    • Element just different node types of one. If a document consists entirely of some empty element, it will have a structure, but this document will not contain any content itself. Online content determines everything, no content of the document is of no value, but the vast majority of content is the text provided .

      //示例:
      <p>这是一个文本</p>
      //‘这是一个文本’ 是一个文本节点
  • Attribute nodes
    • There are other types of nodes. For example, the comment is another node type. But here we introduce is an attribute node.

      //示例
      <p title='book'>这是一本书!</p>
      //title='book'是一个属性节点

2.3 Get node object in three ways

2.3.1 document.getElementById 方法
  • getElementById method has only one parameter, the id attribute value obtained for the element, the id value must be a string type.
<body>
    <div id="box">MJJ</div>
    <ul id="box2">
        <li class="active"></li>
        <li></li>
        <li></li>
    </ul>
        <script>
        var box = document.getElementById('box');
        console.log(box);
        console.dir(box);
    </script>
<body>
//

2.3.2document.getElementsByTagName()方法
  • Tag name acquired by the node object (obtaining a pseudo-array) This method returns a collection of objects element.
//示例1:
<body>
    <div id="box">MJJ</div>
    <ul id="box2">
        <li class="active"></li>
        <li></li>
        <li></li>
    </ul>   
    <script>
        var box = document.getElementsByTagName('div');
        console.log(box);//HTMLCollection [div#box, box: div#box]   
    </script>
</body>
//示例2
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    //css
    <style>
        ul li.active{
            color:red;
        }
    </style>
</head>
<body>
     //html
    <div id="box">MJJ</div>
    <ul id="box2">
        <li>1</li>
        <li>2</li>
        <li>3</li>
    </ul>
//JS:
    <script>
        var lis = document.getElementsByTagName('li');
        //三个li签
        console.log(lis);//HTMLCollection(3) [li, li, li]
        for (var i=0;i<lis.length;i++){//循环将li标签添加class 属性,让CSS渲染
            lis[i].className = 'active';
        }

    </script>
</body>
</html>

//示例3:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    //css
    <style>
        ul li.active{
            color:red;
        }
    </style>
</head>
<body>
     //html
    <div id="box">MJJ</div>
    <ul id="box2">
        <li>1</li>
        <li>2</li>
        <li>3</li>
    </ul>
//JS:
    <script>
        var lis = document.getElementsByTagName('li');
        //三个li签
        console.log(lis);//HTMLCollection(3) [li, li, li]
        for (var i=0;i<lis.length;i++){//循环
            lis[i].onclick = function(){
                this.className = 'active';//鼠标点击获取事件,并将li标签添加class 属性,让CSS渲染
            };
        }

    </script>
</body>
</html>

//示例4:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    //css
    <style>
        ul li.active{
            color:red;
        }
    </style>
</head>
<body>
     //html
    <div id="box">MJJ</div>
    <ul id="box2">
        <li>1</li>
        <li>2</li>
        <li>3</li>
    </ul>
//JS:
    <script>
        var lis = document.getElementsByTagName('li');
        //三个li签
        console.log(lis);//HTMLCollection(3) [li, li, li]
        for (var i=0;i<lis.length;i++){//循环
            lis[i].onclick = function(){
                for (var k=0;k<lis.length;k++){ 
                    lis[k].className = '';//排他思想,让其他li默认class=''
                }

                this.className= 'active';//鼠标点击获取事件,并将li标签添加class 属性,让CSS渲染
            };
        }

    </script>
</body>
</html>
2.3.3document.getElementsByClassName()
  • DOM is also provided by the class name to get some DOM element object.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        ul li.active{
            color:red;
        }
    </style>
</head>
<body>
    <div id="box">MJJ</div>
    <ul id="box2">
        <li class="active">1</li>
        <li>2</li>
        <li>3</li>
    </ul>
        <script>
        var lis = document.getElementsByClassName('active');
        console.log(lis);//HTMLCollection [li.active]
        var box = document.getElementById("box2");
        console.log(box.children);//获得box2下所有的子元素   HTMLCollection(3) [li.active, li, li]
    </script>
</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        ul li.active{
            color:red;
        }
        ul li.att{
            color:blue;
        }
    </style>
</head>
<body>
    <div id="box">MJJ</div>
    <ul id="box2">
        <li class="active">1</li>
        <li>2</li>
        <li>3</li>
    </ul>
//红色蓝色来回切换
    <script>
        var lis = document.getElementsByClassName('active')[0];
        var des = true;
        lis.onclick = function(){
            if (des){
                this.className = 'att';des=false;
            }else{this.className = 'active';
                des = true;
            }
        };
    </script>
</body>
</html>

2.4 style operation

  • box.style. property (CSS attribute with -which the letters capitalized)
//示例1
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #box{
            width: 200px;
            height: 200px;
            background-color: red;
        }
    </style>
</head>
<body>
    <div id="box">MJJ</div>
    <script type="text/javascript">
        // 1.获取事件源对象
        var box = document.getElementById('box');
        // console.log(box);
        //鼠标悬浮,更改样式
        //2.绑定事件
        box.onmouseover = function () {
            box.style.backgroundColor = "green";
            box.style.fontSize = '30px';
            box.style.width = "200px";
            box.style.height = '200px';
        };
        //鼠标离开更改样式
        box.onmouseout = function(){
            box.style.backgroundColor = 'red';
            box.style.fontSize = '15px';
            box.style.width = "400px";
            box.style.height = '400px';
        };
    </script>
</body>
</html>

//示例2:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #box{
            width: 200px;
            height: 200px;
            background-color: red;
        }
    </style>
</head>
<body>
    <div id="box">MJJ</div>
    <script type="text/javascript">
        var box = document.getElementById('box');
        des = true;
        box.onclick = function(){
            if (des){
                box.style.backgroundColor = 'blue';
                des = false;
            }else{
                box.style.backgroundColor = 'green';
                des = true;
            }
        }
    </script>
</body>
</html>

Attribute of Operation 2.5

  • getAttribute () takes one parameter, intends to attribute name queries.
  • setAttribute () word order us to do to modify the value of an attribute node, passing two arguments, the first argument is the name of the second parameter is the attribute value.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .a{
            color:red;
            font-size:30px;
        }
        p.active{
            color:blue;
        }
    </style>
</head>
<body>
    <p title="my class" id = 's21' class="a">21</p>
    <script>
        var p1 = document.getElementById('s21');
        console.log(p1.getAttribute('title'));//my class
        console.log(p1.getAttribute('class'));//a
        p1.setAttribute('class','s20'); //更改属性class  值为s20
        p1.setAttribute('hello','python');//建立属性hello 值为python
        console.log(p1.getAttribute('hello'));//python
        console.log(p1.className);//s20
        console.log(p1.title);//my class
        console.dir(p1);//p#s21.s20 属性
        p1.onclick = function(){
            this.className = this.className + ' active';//加上' active' CSS可用 p.active
        };



    </script>
</body>
</html>

Creating add and delete nodes 2.6

2.6.1 createElement () to create a node
  • This method returns an Element object.

    var newNode = document.createElement(tagName);
  • Adding nodes appendChild

2.6.2 innerText property
  • Just to get or set the text element

    newNode.innerText = '你好';
2.6.3 innerHTML property
  • You can set both text and tags can be set

    newNode.innerHTML = `<a>mjj</a>`

Note: If you want to get the text node objects, you can call directly innerText or innerHTML property to get.

<body>
    <div id="box">MJJ
        <ul id="box2">
            <li class="active">1</li>
            <li>2</li>
            <li>3</li>
        </ul>
    </div>
    <script>
        var box = document.getElementById('box');
        console.log(box.innerText);
        console.log(box.innerHTML);
    </script>
 </body>

//这是innerText结果
//MJJ
//1
//2
//3

//这是innerHTML结果
//MJJ
//      <ul id="box2">
//          <li class="active">1</li>
//          <li>2</li>
//          <li>3</li>
//      </ul>
2.6.4 appendChild () the insertion node
  • Add a new child node after the last child of the specified node.

    appendChild(newNode);
2.6.5insertBefore () the insertion node
  • The method inserts a new child node before an existing child node

    insertBefore(newNode,node);

2.7 removeChild () to remove a node

  • removeChild () method to remove a node from the list of child nodes. If you delete successful, this method returns the removed node, such as a failure, NULL is returned.

  • example:

<body>
    <ul id = 'box'></ul>
    <script type = 'text/javascript'>
        //通过ID获取单个节点对象
        var ul = document.getElementById('box');
        var li1 = document.createElement('li');
        var li2 = document.createElement('li');

        //innerText 只能设置文本格式内容
        li2.innerText = '你好';
        //innerHTML 可以设置HTML格式,如标签
        li1.innerHTML =`<a href='#'>123</a>`;



        //给li1子标签(a)添加属性
        li1.children[0].style.color = 'blue';
        li1.children[0].style.fontSize = '28px';

        //给li2标签添加属性(也就是li)color
        // console.log(li2);//li
        li2.style.color = 'red';


        //将创建好的标签加入ul里。
        ul.appendChild(li1);
        ul.appendChild(li2);


        //将li2更改text值,并在li1前面,插入ul标签li2,
        li2.innerHTML = '第一个';
        ul.insertBefore(li2,li1);
        //将li2标签移除
        ul.removeChild(li2);
    </script>
</body>

2.8 DOM in heigh, clientHeight, offsetHeight property

Intuitive understanding of a wave

  • clientHeight: pattern height + vertical padding (padding area)
  • offsetheight: style vertical padding + height + vertical border-width.
  • height: height height of style, but in the browser display undefined by style.height can set the height, but can not get.
  • Example:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #box{
            height: 300px;
            padding: 10px;
            border: 1px solid red;
            background-color: blue;
        }
    </style>
</head>
<body>
    <div id="box"></div>
    <script type="text/javascript">
        var box = document.getElementById("box");
        console.log(box.height);//undefined 
        console.log(box.offsetHeight);//322
        console.log(box.clientHeight);//320
    </script>
</body>
</html>

3. Event

Events are things that happen in your actions within the system or programming occurs, the system tell you through it in case you wish you can respond to it in some way. For example: If you click a button on a Web page, you may want to respond to this action by displaying a message box.

The main events are:

event Explanation
onclick Mouse click event
onmouseover Rollover events
onMouseOut Mouse out events
onchange The contents of the text box change event
onselect The text box contents are selected event
onfocus The cursor focus event
onblur The cursor out of focus event
onload Page load event

About Event-related learning reference: https://www.cnblogs.com/majj/p/9102401.html

4. Applications

1. The operation of the page through the data

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        li p.name{
            color:red;
        }
        li span.price{
            color:blue;
        }
    </style>
</head>
<body>
        <ul id="box"></ul>
        <script>
        //通过ID获取单个节点对象
        var box = document.getElementById('box');
        var data = [
                {id:1,name:'小米8',subName:'你真好',price:98},
                {id:2,name:'小米6',subName:'你真好2',price:948},
                {id:3,name:'小米4',subName:'你真好3',price:100},
                {id:4,name:'小米2',subName:'你真好4',price:928},
                {id:5,name:'小米10',subName:'你真好5',price:918}
                ];
        //遍历data,以便操作数组每个元素
        for (var i=0;i<data.length;i++){
            //创建标签li  创建节点
            var li = document.createElement('li');
            //插入数据
            li.innerHTML = `<p class="name">${data[i].name}</p>
            <p class="subName">${data[i].subName}</p>
            <span class="price">${data[i].price}元</span>
            `;
            //提交数据
            box.appendChild(li);
        }
    </script>
</body>
</html>

2. Switch picture

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div id = 'box'>
        <img src="images/1.jpg" alt="" id = "imgBox">
    </div>
    <button id="prev">上一张</button>
    <button id="next">下一张</button>
    <script>
        //获取id = 'box'
        var imgBox = document.getElementById('imgBox');
        //获取id = 'next'
        var next = document.getElementById('next');
        //获取id = 'prev'
        var prev = document.getElementById('prev');
        var num = 1;
        //事件点击next,此时执行nextImg函数
        next.onclick = function () {
            nextImg();

        };
        //nextImg函数增加num值获得下一张图片,最后一张做判断,返回第一张
        function nextImg() {
            num ++;
            if (num===5){
                num = 1;
            }
            imgBox.src = `images/${num}.jpg`;

        }
        //事件点击prev 此时执行prevImg()函数
        prev.onclick = function(){
          prevImg();
        };
        //prevImg函数减少num值获得上一张图片,当num=0返回最后一张图片
        function prevImg() {
            num --;
            if (num===0){
                num = 4;
            }
            imgBox.src = `images/${num}.jpg`;
        }
    </script>
</body>
</html>

Guess you like

Origin www.cnblogs.com/xujunkai/p/11028267.html