191120Javascript.md

一、JS基础

1、变量

<script>
    var x = 3;
    var y = 4;
    var name="dongfei", age="19",gender="M";  //多行赋值
    console.log(x+y);
</script>

变量命名规范:

  1. Camel:首字母小写,接下来的字母以大写字母开头,如:myName
  2. Pascal:首字母大写,接下来的字母以大写字母开头,如:MyName
  3. 第一个字符标注数据类型,如:sMyName,s表示string字符串

2、注释

// 单行注释
/* 
多行注释
*/  

3、数据类型

  • Number:包括整型和浮点型
  • String:Unicode字符、数字、标点等组成的序列,由单双引号引用
  • Boolean:true(1)和false(0)
  • Null
  • Undefined:声明了变量,但是没有进行赋值;函数没有返回值那这个函数的数据类型也是Undefined;未定义类型
  • object

typeof:查看数据的数据类型

4、数据类型转换

console.log("hello"+123);  // hello123
console.log("hello"+true);  // hellotrue
console.log(1+true);  // 2
console.log(parseInt(3.14159));  // 3,强制转换
console.log(parseInt('hello'));  // NaN:属于Number数据类型,not a number
console.log(parseFloat('3.14159'));  //3.14159
console.log(eval('1+2+3'));  //6

5、运算符

  • 算术运算符:+, -, *, /, %, ++, --

i++:先输出再加1

++i:先加1再输出

  • 逻辑运算符:==, !=, >, <, >=, <=, &&(与), ||(或), !(非)

6、控制语句

  • if
if(1 == 2){
    alert(1);
}else if(2 == 2){
    alert(2)
}else {
    alert(3)
}
  • switch
var week = "Firday";
switch (week){
    case "Monday":alert("星期一");break;
    case "Tuesday":alert("星期二");break;
    case "Wednesday":alert("星期三");break;
    case "Thursday":alert("星期四");break;
    case "Firday":alert("星期五");break;
    case "Saturday":alert("星期六");break;
    case "Sunday":alert("星期日");break;
    default:alert("输入错误");break;  //默认
}
  • for
var attr = ["aa","bb","cc"];
// 方式一,推荐
for(var i=0; i<attr.length; i++){
    document.write('i: '+ i +'attr: '+ attr[i] +'<br>')
}
// 方式二
for(i in attr){
    document.write('i: '+ i +'attr: '+ attr[i] +'<br>')
}
  • while
var i = 0;
var sum = 0;
while(i <= 100){
    sum += i;
    i++;
}
console.log(sum)
  • try
try {  //正常执行
    console.log("abc");
    throw Error("define error");  //抛出异常
}catch (e){  //异常执行
    console.log(e);
}finally {  //无论正常异常都执行
    console.log("finally");
}

二、ECMA对象

1、string字符串对象

// 创建字符串对象
var str1 = "HelloWorld";
console.log(str1);  //HelloWorld
var str2 = new String("HelloWorld");
console.log(str2);  //String {"HelloWorld"}

// 字符串的属性
console.log(str2.length);  //长度

//字符串的方法
console.log(str2.italics());  //<i>HelloWorld</i> 斜体
console.log(str2.bold());  //<b>HelloWorld</b> 变粗
console.log(str2.anchor());  //<a name="undefined">HelloWorld</a> 超链接
console.log(str2.toUpperCase());
console.log(str2.toLowerCase());
console.log(str2.charAt(3));  //取索引3的字符
console.log(str2.charCodeAt(3));  //取索引3的字符编码
console.log(str2.indexOf("o"));  //取"o"在字符串中第一个的索引,4
console.log(str2.lastIndexOf("o"));  //取"o"在字符串中最后一个的索引,6
console.log(str2.substr(1,3));  //从位置1取3个字符,ell
console.log(str2.substring(1,3));  //从位置1到位置3,el
console.log(str2.slice(-5,-1));  //字符串切片操作,Worl
console.log(str2.replace('World','nihao'));  //替换子字符串,Hellonihao
console.log(str2.split('o'));  //分割字符串,["Hell", "W", "rld"]
console.log(str2.concat('Javascripts'));  //连接字符串,HelloWorldJavascripts

2、Array数组对象

// 创建数组
var arr1 = [123, 'abc', [456,'def'], {'name':'dongfei','age':18}];
var arr2 = new Array(123, 'abc', [456,'def'], {'name':'dongfei','age':18});
var arr3 = [2,3,4,5];
var arr4 = [2,10,3,6,4,5];

//数组的方法
console.log(arr3.join('-'));  //2-3-4-5
console.log(arr1.concat('add'));  //[123, "abc", Array(2), {…}, "add"]
console.log(arr1.toString());  //123,abc,456,def,[object Object],转换为字符串
console.log(arr3.reverse());  //[5, 4, 3, 2],反转
console.log(arr4.sort());  //[10, 2, 3, 4, 5, 6],默认按最高位升序排序
function f(a,b) {
    return a-b
}
console.log(arr4.sort(f));  //[2, 3, 4, 5, 6, 10],按大小排序
console.log(arr2.slice(1,3));  //数组切片
console.log(arr2.splice(1,2));  //对子数组进行删除插入操作

//push和pop,出栈和入栈,栈:后入先出
var arr5 = [3,5,8,9];
arr5.push([6,4]);
arr5.push('hello',7);
console.log(arr5 );  //[3, 5, 8, 9, Array(2), "hello", 7]
console.log(arr5.pop());  //7

//shift和unshift,栈操作
var arr6 = [3,5,8,9];
arr6.unshift(['abc',123]);
arr6.unshift('hello',true);
console.log(arr6);  //["hello", true, Array(2), 3, 5, 8, 9]
console.log(arr6.shift());  //hello

3、函数对象

//函数创建一
function f(x,y) {
    alert('hello world');
    return true
}
console.log(f());

//函数创建二
var obj = new Function('x','y','alert(\'hello world\'+x+y)');
obj(3,4);
//
console.log(f.length);  //函数参数的长度
//arguments
function foo() {
    console.log(arguments[0]);  //a
    console.log(arguments[1]);  //b
    console.log(arguments[2]);  //c
    console.log(arguments[3]);  //undefined
}
foo('a','b','c');

//加法计算器
function add() {
    var sum = 0;
    for (var i=0;i<arguments.length;i++){
        sum += arguments[i];
    }
    return sum
}
console.log(add(1,3,4,6,8));

//匿名函数,方式一
var bar = function (arg) {
    return arg
};
bar('hi')

//匿名函数,方式二
(function (arg) {
    return arg
})('bar2')

三、DOM对象

  • 浏览器对象模型,可以对浏览器窗口进行访问和操作,使JavaScript有能力与浏览器交互

1、window对象

  • window对象的方法
alert('alert');  //告警弹窗
var ret = confirm('confirm'); console.log(ret); //选择弹窗(确定返回true|取消返回false)
var ret2 = prompt('prompt'); console.log(ret2); //输入弹窗(返回输入的内容)

open('https://www.baidu.com/');  //打开新的窗口
close()  //关闭当前窗口


function f() {
    console.log('Interval...')
}
var S1 = setInterval(f,1000);  //周期执行,1000ms一次
clearInterval(S1)  //取消S1定时器

var S2 = setTimeout(f,1000);  //只执行一次
clearTimeout(S2);
  • setInterval实例
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
    #id1{
        width: 200px;
        height: 50px;
    }
</style>
<body>
<input type="text" id="id1" onclick="begin()" />
<button onclick="end()">停止</button>
<script>
    function showTime() {
        var current_time = new Date().toLocaleString();
        var ele = document.getElementById('id1');
        ele.value = current_time;
    }
    var clock1;
    function end() {
        clearInterval(clock1);
        clock1 = undefined;
    }
    function begin() {
        if(clock1==undefined){
            showTime();
            clock1 = setInterval(showTime,1000);
        }
    }
</script>
</body>
  • History对象
<a href="js_lesson04.html">click</a>
<button onclick="history.forward()">go</button> //前进
<button onclick="history.back()">back</button>  //后退
<button onclick="history.go(1)">go</button>  //前进
<button onclick="history.go(-1)">back</button>  //后退
  • Location对象
function f() {
    location.reload();  //刷新
    location.replace('https://www.baidu.com');  //替换当前页面,没有后退操作
    location.assign('https://www.baidu.com');  //链接至百度,可以后退至上一页面
}

2、Document.Element对象

var ele_p = document.getElementsByClassName('p1')[0];  //使用class获取p标签节点对象
var ele_div = document.getElementById('div1');  //使用id获取标签节点对象
//节点对象自生属性
console.log(ele_p);
console.log(ele_p.nodeName);  //P
console.log(ele_p.nodeType);  //1
console.log(ele_p.nodeValue); //null
console.log(ele_p.innerHTML); //ppppp,取节点中的文本
ele_p.innerHTML = 'ppppp2';  //控制节点,修改节点文本
//节点对象导航属性
var ele_1 = ele_p.parentNode;  //查找父节点
var ele_2 = ele_p.nextElementSibling;  //查找下一个标签节点
var ele_3 = ele_p.previousElementSibling;  //查找上一个标签节点
var ele_4 = ele_p.children;  //所有子标签
var ele_5 = ele_p.firstElementChild;  //第一个子标签
var ele_6 = ele_p.lastElementChild;  //最后一个子标签

3、Document.Event对象

onclick        当用户点击某个对象时调用的事件句柄
ondblclick     当用户双击某个对象时调用的事件句柄
onfocus        元素获得焦点
onblur         元素失去焦点
onchange       域的内容被改变
onkeydown      某个键盘按键被按下
onkeypress     某个键盘按键被按下并松开
onkeyup        某个键盘按键被松开
onload         一张页面或一幅图像完成加载
onmousedown    鼠标按钮被按下
onmousemove    鼠标被移动
onmouseout     鼠标从某元素移开
onmouseover    鼠标移到某元素之上
onmouseleave   鼠标从元素离开
onselect       文本被选中
onsubmit       确认按钮被点击
<body>
<!--获得焦点和失去焦点时做的动作-->
<input type="text" id="search" value="please input" onfocus="f1()" onblur="f2()" />
<script>
    function f1() {
        var ele = document.getElementById('search');
        if(ele.value=="please input"){
            ele.value = ""
        }
    }
    function f2() {
        var ele = document.getElementById('search');
        if(!ele.value){
            ele.value = "please input"
        }
    }
</script>
</body>

补充1:事件绑定

<body>
<div>
    <div class="div1">divdiv</div>
    <div class="div1">divdiv</div>
    <div class="div1">divdiv</div>
    <div class="div1">divdiv</div>
    <p>ppppp</p>
</div>
<script>
    var ele = document.getElementsByClassName('div1');
    for(var i=0;i<ele.length;i++){
        ele[i].onclick=function () {
            alert('div');
        }
    }
</script>
</body>

补充2:this参数

<div class="div1" onclick=f(this)>divdiv</div>  //点击此标签时在函数内可以通过参数获取此div对象
  • onsubmit事件
<body>
<form action="" id="form01">
    <input type="text" name="username">
    <input type="submit" value="提交">
</form>

<script>
    var ele=document.getElementById('form01');
    ele.onsubmit=function (e) {  //e:点击事件的信息,如鼠标的位置等
        alert('已提交');
//        return false  //返回false则会拦截表单提交
        e.preventDefault()  //阻止默认发生的事件
    }
</script>
</body>
  • 阻止事件传播
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .outer{
            width: 300px;
            height: 300px;
            background-color: antiquewhite;
        }
        .inner{
            width: 100px;
            height: 100px;
            background-color: rebeccapurple;
        }
    </style>
</head>
<body>
<div class="outer">
    <div class="inner"></div>
</div>

<script>
    var ele = document.getElementsByClassName('inner')[0];
    ele.onclick=function (e) {
        alert('inner');
        e.stopPropagation();  //阻止事件传播
    };
    var ele2 = document.getElementsByClassName('outer')[0];
    ele2.onclick=function () {
        alert('outer');
    };
</script>
</body>

四、Node节点的增删改查

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .div1,.div2,.div3,.div4{
            width: 300px;
            height: 100px;
        }
        .div1{
            background-color: green;
        }
        .div2{
            background-color: yellow;
        }
        .div3{
            background-color: lemonchiffon;
        }
        .div4{
            background-color: red;
        }
    </style>
</head>
<body>
<div class="div1"><button onclick="add()">add</button>div1</div>
<div class="div2"><button onclick="del()">del</button>div2</div>
<div class="div3">
    <button onclick="change()">change</button>
    <p>div3</p>
</div>
<div class="div4">div4</div>
</body>
</html>

1、增

function add() {
    var ele = document.createElement('p');  //创建一个p标签
    ele.innerHTML='new p';  //给p标签赋值
    var father = document.getElementsByClassName('div1')[0];  //获取需要添加的位置
    father.appendChild(ele);  //给父标签加子标签p
}

2、删

function del() {
    var father = document.getElementsByClassName('div1')[0];
    var son = father.getElementsByTagName('p')[0];
    father.removeChild(son);
}

3、改

function change() {
    var img = document.createElement('img');
    img.src = 'run.jpg';  //添加属性
    var ele = document.getElementsByTagName('p')[0];
    var father = document.getElementsByClassName('div3')[0];
    father.replaceChild(img,ele);  //img对象替换ele对象
}

4、改css

function change() {
    var img = document.createElement('img');
    img.src = 'run.jpg';  //添加属性
    img.style.width = '100px';
    img.style.height = '100px';  //修改标签的style
    var ele = document.getElementsByTagName('p')[0];
    var father = document.getElementsByClassName('div3')[0];
    father.replaceChild(img,ele);  //img对象替换ele对象
}

五、模态对话框

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .content {
            height: 1800px;
            background-color: rebeccapurple;
        }
        .shade {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: white;
            opacity: 0.5;
        }
        .model{
            width: 200px;
            height: 200px;
            background-color: bisque;
            position: absolute;
            top: 50%;
            left: 50%;
            margin-top: -100px;
            margin-left: -100px;
        }
        .hide{
            display: none;
        }
    </style>
</head>
<body>
<div class="content">
    <button onclick="show()">show</button>
</div>
<div class="shade hide"></div>
<div class="model hide">
    <button onclick="cancel()">cancel</button>
</div>

<script>
    function show() {
        var ele_shade = document.getElementsByClassName('shade')[0];
        var ele_model = document.getElementsByClassName('model')[0];
        ele_shade.classList.remove('hide');
        ele_model.classList.remove('hide');
    }
    function cancel() {
        var ele_shade = document.getElementsByClassName('shade')[0];
        var ele_model = document.getElementsByClassName('model')[0];
        ele_shade.classList.add('hide');
        ele_model.classList.add('hide');
    }
</script>
</body>
</html>

六、正反选框示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<button onclick="selectAll()">全选</button>
<button onclick="cancelAll()">取消</button>
<button onclick="reverseAll()">反选</button>
<hr>
<table border="1px">
    <tr>
        <td><input type="checkbox"></td>
        <td>111</td>
        <td>111</td>
        <td>111</td>
    </tr>
    <tr>
        <td><input type="checkbox"></td>
        <td>222</td>
        <td>222</td>
        <td>222</td>
    </tr>
    <tr>
        <td><input type="checkbox"></td>
        <td>333</td>
        <td>333</td>
        <td>333</td>
    </tr>
</table>

<script>
    function selectAll() {
        ele_inputs = document.getElementsByTagName('input');
        for (var i = 0;i < ele_inputs.length; i++) {
            ele_inputs[i].checked=true;
        }
    }
    function cancelAll() {
        ele_inputs = document.getElementsByTagName('input');
        for (var i = 0;i < ele_inputs.length; i++) {
            ele_inputs[i].checked=false;
        }
    }
    function reverseAll() {
        ele_inputs = document.getElementsByTagName('input');
        for (var i = 0;i < ele_inputs.length; i++) {
            ele_inputs[i].checked = !ele_inputs[i].checked;
        }
    }

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

七、select 二级联动

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<select name="" id="provinces">
    <option value="">选择省份</option>
</select>
<select name="" id="citys">
    <option value="">选择城市</option>
</select>
<script>
    var data = {"河北省":["石家庄","张家口","保定","衡水"],"河南省":["郑州"]};
    // console.log(data);  //{河北省: Array(4), 河南省: Array(1)}
    // console.log(typeof data);  //object
    // console.log(data["河北省"]);  //["石家庄", "张家口", "保定", "衡水"]
    // console.log(data.河南省);  //["郑州"]
    var ele_provinces = document.getElementById('provinces');
    var ele_citys = document.getElementById('citys');
    for (var i in data){
        var ele = document.createElement('option');
        ele.innerHTML = i;
        ele_provinces.appendChild(ele);
    }
    ele_provinces.onchange = function () {
        console.log(this); // this是select标签
        console.log(this.selectedIndex);  //被选中的option的索引值
        console.log(this.options[this.selectedIndex]);  //被选择的option的标签
        var citys = data[this.options[this.selectedIndex].innerHTML];
        ele_citys.options.length = 1;
        for (var i=0;i<citys.length;i++){
            var ele = document.createElement('option');
            ele.innerHTML = citys[i];
            ele_citys.appendChild(ele);
        }
    }
</script>
</body>
</html>
posted @ 2020-01-03 18:06  生生不息.连绵不绝  阅读(255)  评论(0编辑  收藏  举报