JS学习
一、基础内容
变量类型只有var,不能以数字开头
局部变量使用let
// 定义变量
var num =1;
//条件控制使用if语句与java类似
alert("true");//弹窗
console.log();//控制台打印
在浏览器中调试
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FWOnFoPC-1637636231904)(C:\Users\AOC\AppData\Roaming\Typora\typora-user-images\image-20211111172114838.png)]
二、数据类型
1、数值
number JS不区分小数和整数
NaN=不是一个数字
Infinity表示无限大
2、字符串
‘abc’ “abc”
正常字符使用单引号或者双引号
转义字符\
\'
\n //换行
\t
\u4e2d //Unicode字符
\x41 //ASCALL码
`` //可以写多行字符串
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gmNUkp6I-1637636231906)(C:\Users\AOC\AppData\Roaming\Typora\typora-user-images\image-20211115110213710.png)]
模板字符串
${xx} //可以在``中使用该符号取出字段的值,用于拼接动态字符串
字符串方法
字符串.length ----长度
可以利用下标输出
.toUpperCase() --变换大写
.toLowCase() --变换大写
.indexOf(‘t’)–获取该字符下标
.substring(n)–截取第n个后面的字符串
3、布尔值
true false
4、逻辑运算
&& 与
|| 或
! 非
5、比较运算符
= //赋值
== //等于(类型不一样,值一样也会相等)
=== //绝对等于(类型和值都一样)
6、浮点数
尽量避免浮点数计算,会有精度缺失
//ture
console.log(Math.abs(1/3-(1-2/3))<0.000000001);
//false
console.log(1/3===(1-2/3));
7、数组
使用【】
var arr = [1,2,3,4,'hello',null,true];
//取值
arr[4]
//若没值增显示undefined
javascript中不用相同对象
方法:
长度----.length
数组可变值
长度可变
slice()截取,相当于substring
push–添加元素进入数组尾部
pop()–删除尾部元素
unshift()—添加元素进入数组头部
shift()—删除头部 元素
concat()合并成新的数组
join("")连接符,打印字符串使用。
多维数组:
arr = [[1,2],[3,4],["a","b"]]
arr[1][1]
4
8、对象
使用{}
对象中使用
var 对象名 = {
属性名:属性值,
属性名:属性值,
属性名:属性值
}
var person = {
name:"bango",
age:42,
tags:['js','java','html']
}
//取值
person["age"]//对象中的值
person["tags"][1]//对象中数组的值
对象中的属性使用,隔开,最后一个不需要
使用一个不存在的对象只会undefinded,不会报错
delete—动态删除对象属性
.属性名=属性值,增加对象属性
判断元素是否在对象中
‘属性名’ in 对象名
hasOwnProperty("")方法判断是否拥有该属性
foreach循环
对象.foreach(function(value){
console.log(value)
})
for…in
for (var num in age){
if(age.hasOnwProperty(num)){
console.log(age[num])
}
}
9、strict严格模式
增加
'use strict';
严格检查模式,预防JavaScript的随意性导致报错
必须写在第一行
10、Map和Set
与java类似,使用键值对储存,get和set方法,delete删除
Set集合可以去重,使用add添加,delete删除
for…of
可以打印map和set
for( var num of map){
console.log(num);
}
三、函数(方法)
1、定义函数(方法)
// 第一种
function 函数名(x){
内容
}
//第二种
var 函数名 = function(x){
内容
}
2、参数
arguments包含所有传进来的参数
添加…rest
rest只能放在最后一个参数,为未命名参数的数组
四、变量作用域
var:
若在函数内部声明,则函数外部不可使用(闭包)
定义放在最前面
JS中是从内向外查找变量,
全局函数
全局变量在函数外,会默认绑定到对象window中
规范:自定义一个全局变量
//唯一全局变量、
var xxx = {};
//定义全局变量
xxx.name = 'hanhan';
xxx.add = function(a,b){
return a+b;
}
自己的代码全部放在自己的全局变量中。
let:
局部变量,有一定的作用区间
const:
静态变量,不可修改
五、方法
1、定义方法
把函数放入对象中
var bango = {
name: 'tom',
birth: 1994,
age: function(){
var now = new Date().getFullYear();
return now-this.birth;
}
}
//使用方法
//属性
bango.name
//方法,方法一定要带()
bango.age()
this代表
2、apply
apply可以控制this指向
getAge.apply(bango,[]);
function getAge(){
var now = new Date().getFullYear();
return now-this.birth;
};
var bango = {
name: 'tom',
birth: 1994,
age: getAge
};
3、内部对象
Date
var now = new Date();
//获取年份
now.getFullYear();
//获取月份(0-11)
now.getMonth();
//获取日
now.getDate();
//获取星期
now.getDay();
//获取小时
now.getHours();
//获取分钟
now.getMinutes();
//获取秒
now.getSeconds();
//获取毫秒
now.getMilliseconds();
//获取时间戳
now.getTime();
时间戳转换为时间
new Date(时间戳)
now.toLocaleString()
JSON
转换stringify和parse
//对象转json字符串
let jsonInfo = JSON.stringify(info)
//json字符串转对象
let stringInfo = JSON.parse(jsonInfo);
Class
class Student{
constructor(name) {
this.name = name ;
}
hello(){
alert('hello')
}
}
//继承
class xiaoxuesheng extends Student{
constructor(name,grade) {
super(name);
this.grade = grade;
}
myGrade(){
alert('woshixiaoxues')
}
}
var xiaoming = new Student('xiaoming');
var xiaowang = new xiaoxuesheng("xiaowang",5);
六、操作BOM对象
BOM:浏览器对象模型
window代表浏览器窗口
//浏览器的宽高
window.innerWidth
window.outerWidth
window.innerHeight
window.outerHeight
navigator.appVersion
'5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.9 Safari/537.36'
navigator.userAgent
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.9 Safari/537.36'
可以使用navigator来查看用户使用的情况
大多数不会使用navigator对象,会被人修改
screen
代表屏幕尺寸
location
代表当前网页的URL信息
reload //刷新
location.assign('')//访问跳转
document
document.title = '';//修改网页标题
document.getElementById(''),//获取网页树节点
document.cookie//获取cookie
//cokie设置为httpOnly;
history
history.forward()//前进
history.back()//后退
七、操作DOM对象
1、核心
网页时一个dom树形结构
更新:
遍历:
删除:
添加:
获取dom节点
//原生代码
// 对应css选择器
var h1 = document.getElementsByTagName('h1');
var p1 = document.getElementById('p1');
var p2 = document.getElementsByClassName('p2');
var father = document.getElementById('father');
var childrens = father.children;//获取父节点下的子节点
// father.firstChild第一个子节点
// father.lastChild最后一个子节点
更新节点
innerText//修改文本值
innerHTML//修改样式可以解析HTML标签
style.color//文字颜色
style.fontSize//字体大小
删除节点
先获取父节点,再通过父节点删除自己
.parentElement;//获取父节点
注意删除多个节点是,数量是在动态变化的。
新增节点
转移一个节点
<body>
<p id="js">JavaScript</p>
<div id="list">
<p id="se">JavaSE</p>
<p id="ee">JavaEE</p>
<p id="me">JavaME</p>
</div>
</body>
<script>
var js = document.getElementById('js'),
list = document.getElementById('list');
</script>
list.appendChild(js)//使用appendChild
创建一个标签并添加
var js = document.getElementById('js'),
list = document.getElementById('list');
var newP = document.createElement('p');
newP.id = 'newP';
newP.innerText = 'hello';
list.appendChild(newP);
var script1 = document.createElement('script');
script1.setAttribute('type','text/javascript')
//通过setAttribute可以设置任意的值
创建特殊标签并添加
//style标签
var head = document.getElementsByTagName('head')[0];//获取head标签
//新建css标签并添加样式
var css = document.createElement('style');
css.setAttribute('type','text/css');
css.innerHTML = 'body{ background-color: red}';
//放入head标签
head.appendChild(css);
//script标签
var script1 = document.createElement('script');//创建标签
script1.setAttribute('type','text/javascript');
//获取body标签并放入新标签
var body = document.getElementsByTagName('body')[0];
body.appendChild(script1);
插入节点
var ee document.getElementById('ee');
var js document.getElementById('js');
var list document.getElementById('list');
//插入再目标节点前
list.insertBefore(js,ee);
//insertBefore(新节点,目标节点)
八、操作表单(验证)
1、表单输入框类型
文本框 text
<form action="post">
<span>用户名:</span><input type="text" id="username" >
</form>
var input = document.getElementById('username');
input.value//获取输入框的值
input.value ='123';//给输入框赋值
下拉框
单选框 radio
<p>
<span>性别:</span>
<input type="radio" name="sex" value="man" id="boy">男
<input type="radio" name="sex" value="woman" id="girl">女
</p>
//获取节点
var boy = document.getElementById('boy');
var girl = document.getElementById('girl');
boy.value//获取选项框的value值
'man'
//查看单选框的状态
boy.checked
true
girl.checked
false
//赋值单选框赋值
boy.checked = ture
多选框 checkbox
隐藏域 hidden
密码框 password
2、表单提交验证
通过dom来获取input值,再提交时调用方法进行判断,表单中属性onsubmit中调用。
<form action="https://www.baidu.com" method="post" onsubmit="check()">
<p>
<span>用户名:</span><input type="text" name="username" id="username" >
</p>
<p>
<span>密码: </span><input type="password" id="password" >
</p>
<input type="hidden" id="md5" name="password" />
<p>
<span>性别:</span>
<input type="radio" name="sex" value="man" id="boy">男
<input type="radio" name="sex" value="woman" id="girl">女
</p>
<button type="submit" >提交</button>
</form>
输入框没有name属性时不会传递参数
//前端密码传递加密使用md5,并设置隐藏域
//<script src="http://cdn.bootcss.com/blueimp-md5/2.10.0/js/md5.min.js"></script>
var username = document.getElementById('username');
var password = document.getElementById('password');
var passw = document.getElementById('md5');
passw.value= md5(password.value);
password.value='****';
console.log('usn--->'+username.value);
console.log('psw-->'+password.value);
console.log(mdxx5.value);
九、JQuery库
1、获取jquery
下载:
https://www.jq22.com/jquery/jquery-3.5.1.zip
cdn引用:
<script crossorigin="anonymous" integrity="sha512-n/4gHW3atM3QqRcbCn6ewmpxcLAHGaDjpEBu4xZd47N0W2oQ+6q7oc3PXstrJYXcbNU1OHdQ1T7pAP+gi5Yu8g==" src="https://lib.baomitu.com/jquery/3.6.0/jquery.js"></script>
2、jquery使用
$(selector).action()
<body>
<!--
公式:$(selector).action()
-->
<a href="" id="test-jquery">点击</a>
</body>
<script>
$('#test-jquery').click(function(){
alert('hello');
})
</script>
3、 网页加载完成后操作
//当网页元素加载完成后执行
$(document).ready(function(){
})
//简化为
$(function(){
})
例子:获取鼠标坐标
<div id="test">
<div id="info">
mouse:<span id="mouseMove"></span>
</div>
<div id="divMove">
<div id="divText">
<span id="text">在这里移动试试</span>
</div>
</div>
</div>
//当网页元素加载完成后执行
$(function(){
$('#divMove').mousemove(function(e){
$('#mouseMove').text('x:'+e.pageX+'y:'+e.pageY);
})
});
4、隐藏显示,淡入淡出
<div id="demo1">
<p id="demo">jquery</p>
</div>
<button id="btn1" >隐藏</button>
<button id="btn2" >显示</button><br><br>
<div id="color-father">
<div id="color1" ></div>
<div id="color2" ></div>
</div>
<button id="btn3" >淡出</button>
<button id="btn4" >淡入</button>
<input id="num" type="number" max="1" min="0.1" step="0.05" />
<button id="btn5" >调整透明度</button>
//隐藏
$('#btn1').click(function(){
$('#demo').hide();
});
//显示
$('#btn2').click(function(){
$('#demo').show();
});
//淡出
$('#btn3').click(function(){
$('#color1').fadeOut('slow');
$('#color2').fadeOut('slow');
});
//淡入
$('#btn4').click(function(){
$('#color1').fadeIn('slow');
$('#color2').fadeIn('slow');
});
//根据输入框取值,并调用淡化
$('#btn5').click(function(){
myInfo['num'] = $('#num').val();
if(myInfo.num > 1 || myInfo.num <0.01){
alert('请输入0.1~1的数');
}
$('#color1').fadeTo('slow',myInfo.num);
$('#color2').fadeTo('slow',myInfo.num);
});
//隐藏显示切换
toggle()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lYE3E0oh-1637636231907)(C:\Users\AOC\AppData\Roaming\Typora\typora-user-images\image-20211119100922658.png)][外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yEkf7ixe-1637636231909)(C:\Users\AOC\AppData\Roaming\Typora\typora-user-images\image-20211119100932600.png)]
4、操作DOM元素
获取
var text = $('#list li[name=python]').text()//文本内容
$('#list').html()//html标签
更新
$('#list li[name=python]').text('C++')//文本内容
$('#list').html('<strong>123</strong>');//html标签
5、操作CSS文件
设置元素
$('#list li[name=python]').css({"color": "#ff0011"});//设置css属性
$('#list li[name=python]').css("color");//获取css某个属性的值
6、获取页面信息
$(window).width()
$(window).height()
7、ajax请求
$.ajax({
//请求方法
method:'get',
//url地址
url:"http://192.168.5.160:8083/daily/getDailyById",
//请求参数
data:{"id":id},
//请求头
headers:{"token":"c63bf5e02e57ca5fc0099a2f119cc08741ed34545241354c0f2d5daa5b2ae111"},
//访问成功回调
success:function(data){
let jsonInfo = JSON.stringify(data);
let info = JSON.parse(jsonInfo);
//判断返回的code
if(info.code === 500){
alert(info.message);
}
console.log(info.data);
//创建表格信息
var name = $('<td data-label="Name"></td>');
name.text(info.data.info.studentName);//放入信息
var content = $('<td data-label="Age"></td>');
content.text(info.data.info.content);//放入信息
var problem = $('<td data-label="Job"></td>');
problem.text(info.data.info.problem);//放入信息
//创建外包
var tr = $('<tr></tr>')
tr.append(name);
tr.append(content);
tr.append(problem);
//创建表单行
var tbody = $('<tbody></tbody>')
tbody.append(tr);
//放入table中
$('#table').append(tbody);
},
//请求失败调用
error:function(){
alert("请求失败");
}
});
页面显示
<table id="table">
<thead>
<tr><th>姓名</th>
<th>日报内容</th>
<th>今日问题</th>
</tr></thead>
</table>
请求获取到数据自动添加到表单中
jsonInfo);
//判断返回的code
if(info.code === 500){
alert(info.message);
}
console.log(info.data);
//创建表格信息
var name = $(’’);
name.text(info.data.info.studentName);//放入信息
var content = $(’’);
content.text(info.data.info.content);//放入信息
var problem = $(’’);
problem.text(info.data.info.problem);//放入信息
//创建外包
var tr = $(’’)
tr.append(name);
tr.append(content);
tr.append(problem);
//创建表单行
var tbody = $(’’)
tbody.append(tr);
//放入table中
$(’#table’).append(tbody);
},
//请求失败调用
error:function(){
alert(“请求失败”);
}
});
页面显示
```html
<table id="table">
<thead>
<tr><th>姓名</th>
<th>日报内容</th>
<th>今日问题</th>
</tr></thead>
</table>
请求获取到数据自动添加到表单中