<h2 onclick="alert('hello,我是行内js')">点我!h2>
<script >
alert("我是内部js,这是标准位置")
script>
<script src="js/test01.js">script>
注意:上述三种方式并不存在相对优先级,而是根据具体的位置决定。比如下列代码:
作为弱语言,js使用var定义变量。但是有具体的数据类型
使用typeof查看当前数据类型。
使用parseInt、parseFloat强制转换。
存在严格等于(=)和非严格等于()。前者数据类型与数值均相等;后者只判断数值。
<script>
var a = 1;
var b = 3.14;
var c = 'hello';
var e = true;
var ae = a + e;
console.log(a + b + typeof (a+b))//4.140000000
console.log(c + typeof (c)) //hellostring
console.log(e + typeof (e)) //trueboolean
console.log(ae + typeof (ae))//boolean运算变为具体数值:2
console.log(parseInt(b) + typeof (parseInt(b)))//转为整数
console.log(parseFloat(a) + typeof (parseFloat(a)))//转为浮点
console.log(true == 1);//非严格等于 true
console.log(true === 1);//严格等于 flase
script>
<script>
var str="hello";
//length:获取字符串的长度:
console.log(str.length);//5
//toUpperCase/toLowerCase :转大小写
console.log(str.toUpperCase()+"转大写");// HELLO
//charAt(下标) : 返回某个下标的字符
console.log(str.charAt(0));//h
console.log("我".charCodeAt(0))//汉字'我'的UniCode编码
//indexof(字符)、lastIndexof(字符):字符出现的下标
console.log(str.indexOf("h")+"和"+str.lastIndexOf('l'));//0和3
//substring(开始,结束):截取字符串中一部分
console.log(str.substring(0,2))//he 截取
//replace(旧的,新的):替代
console.log(str.replace("he","xx"))//xxllo
//split(分割的节点):字符串的分割,返回数组
var str1="h,e,l,l,o";
var arr=str1.split(',');
console.log("分割成:"+arr.length+"第2份是:"+arr[1]); //5 e
script>
初始化数组的三种方式
<script>
var arr=new Array();//方式1
arr[0]=0;arr[1]=1;
//方式2
var arr=new Array(10,"hello",true);
//方式3
var arr = [10, "hello", true]
for (var i = 0; i < arr.length; i++) {
console.log(arr[i])//10 hello true
}
script>
数组的常用方法:
toString()、join(中间连接)、concat(尾部连接)、slice(截取)、reverse(反转)、sort(字符排序!)、sort(函数名)
<script>
//toString:转为字符串
console.log(arr.toString());//10,hello,true
//将数组中的每个元素用连接符号连接成一个新的字符串。
console.log(arr.join("-"));//10-hello-true
//将原来的数组连接新元素,未改动原数组
console.log(arr.concat("husky","zoe"));//[10, "hello", true, "husky", "zoe"]
//提取一部分
console.log(arr.slice(1,3))// ["hello", true]
//反转
console.log(arr.reverse());//["hello", true,10]
console.log(arr)//["hello", true,10] ,原数组发生变化!
//排序针对字符(先比较首字符,依次后推)
console.log(arr.sort());// [10, "hello", true]
//若想对数字排序,需要自定义函数
var arr1=[31,12,111,444];
arr1.sort(f);
function f(a,b) {
return a-b;
}
console.log(arr1);//[12,31,111,444]
script>
<script>
//这里以随机数为例
var i=Math.random()*10;
console.log(i+" "+parseInt(i));//不会四舍五入,直接取首位:5.62…… -> 5
console.log(i+" "+Math.round(i))//四舍五入
script>
Number() 函数把对象的值转换为数字。具体链接
<script>
console.log(Number("999")+1)//将字符串转为数字类型 1000
console.log(Number(3.14159).toFixed(2));//包留几位小数 3.14
console.log(Number(123000).toExponential())//用指数法表示 1.23e5
script>
两种方式定义正则表达式。正则表达式使用具体上网查阅
<script>
//方式1:普通字符串定义(/^开始 $/结束)
var name = "abc123";
var reg = /^[a-zA-Z0-9]{4,8}$/;
if (reg.test(name)) {
console.log("账户验证通过!")
}
//方式二,使用new方式定义正则表达式(^开始 $结束)
var password = "qwe12345";
var regpwd = new RegExp("^[a-zA-Z0-9]{6,8}$")
if (regpwd.test(password)) {
console.log("密码验证通过!")
}
script>
<script>
var time = new Date();
console.log(time)
// Mon Jan 25 2021 13:10:01 GMT+0800 (中国标准时间)
console.log(
time.getFullYear() + "年" + (time.getMonth() + 1) + "月" + time.getDate() + "日"
+ time.getHours() + "点" + time.getMinutes() + "分" + time.getSeconds()
+ "秒";
//2021年1月25日13点14分5秒
)
script>
<script>
/*无返回值*/
f(1, 1);
function f(a, b) {
console.log(a + b);
}
/*有返回值*/
console.log(f1(1, 1));
function f1(a, b) {
return a + b;
}
/*获取参数对象 arguments*/
f2(1, 2, 3);
function f2(a, b, c) {
console.log(arguments.length);//3
console.log(arguments[0])//1
}
//匿名函数
var fn = function (a, b) {
return a * b;
}
console.log(fn(3, 4))
script>
isNAN:检查是否为非数字。非数字就为true
eval:计算 JavaScript 字符串
encodeURI 与 decodeURI。转码与解码
<script>
console.log(isNaN(123)+" "+isNaN("123")+" "+isNaN("hello")); //false false true
console.log(eval("1+3")); //4
var str="奥术跃迁";
console.log(str1=encodeURI(str));
console.log(decodeURI(str1));
script>
<script>
//统计方法执行了多少次.可定义一个全局变量使用,但不安全
//使用局部变量,外部无法访问,只可以return返回出去,但无法避免的内部变量每次从0开始。
function test1() {
var count=0;//局部变量
function add() {
return count+=1;
}
return add;
}
var fn=test1();//fn => function add(){return count+=1;}
fn();
fn();
console.log(fn()); //3
script>
<script>
//确认框
var b = confirm(`like ?`);
if (b) {
document.write("yes i like too
")
} else {
document.write("oh so sry
")
}
//输入框
var name = prompt("like who?")
document.write("i know you like " + name)
script>
<body>
<form action="404.html" onsubmit="return login()">
<p> 账号<input id="username">p>
<p>密码 <input type="password" id="pwd">p>
<input type="submit" value="提交">
form>
<script>
function login() {
var name = document.getElementById("username").value;
if (name == "") {
alert("账户为空!");
return false;
}
return true;
}
script>
body>
<table border="1" cellspacing="0">
<tr>
<td><input type="checkbox" onchange="quan(this)" /> 全选td>
<td>名称td>
<td>单价td>
tr>
<tr>
<td><input type="checkbox" name="one" />1td>
<td>功能性饮料-尖叫td>
<td>4.0td>
tr>
…
table>
<script>
function quan(all) {
var arr=document.getElementsByName("one");
for (var i=0;i<arr.length;i++){
// 将全选框的状态,赋值给每一个复选框
arr[i].checked=all.checked;
}
}
script>
getElementsByTagName:通过标签名称获得元素节点对象集
<script>
var rows = document.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++) {
if (i % 2 == 0) {
rows[i].style.backgroundColor = "pink";
}
}
script>
修改HTML DOM意味着许多不同的方面:
<body>
<p id="p1">我是修改元素的内容与样式案例p>
<button onclick="test()">点我改内容button>
<button onclick="test1()">点我样式button>
<script>
function test() {
//innerHTML 从对象的起始位置到终止位置的全部内容,包括Html标签
document.getElementById("p1").innerHTML = "Zoe";
//innerText 从起始位置到终止位置的内容,但它去除Html标签
//document.getElementById("p1").innerText="like";
}
function test1() {
document.getElementById("p1").style.color = "pink";
document.getElementById("p1").style.fontFamily = "微软雅黑";
document.getElementById("p1").style.fontSize = "20px";
}
script>
body>
<body>
<button onclick="add()">添加button>
<button onclick="del()">删除button>
<button onclick="rep()">替换button>
<div>div>
<script>
//通过父节点进行增、删、替换 xxxChild(Node);
function add() {
var img = document.createElement("img");
img.setAttribute("src", "../imgs/zoe.jpg");
img.setAttribute("id", "zoe");
var divs = document.getElementsByTagName("div");
//简写:document.getElementsByTagName("div")[0];
divs[0].appendChild(img);
}
function del() {
//var img = document.getElementById("zoe");此方式如果先替换,将无法删除。
var img=document.getElementsByTagName("img")[0];
img.parentNode.removeChild(img);//必须通过父节点才能删除子节点
}
function rep() {
//方式一:修改属性
var img = document.getElementById("zoe");
/*zoe.setAttribute("src","../imgs/wrlt.jpg");*/
//方式二:真正意义上的替换
var newimg = document.createElement("img");
newimg.setAttribute("src", "../imgs/zoe3.jpg");
img.parentNode.replaceChild(newimg, img);
}
script>
body>
<body onload="test()">
<p>账号<input onfocus="test1()" onblur="test2()" id="1">p>
<p>密码<input type="password">p>
<script>
/*function test() {
窗口事件:仅在body和frameset有效;onload:当文档被载入时执行
document.write("233");
} */
function test1() {
document.getElementById("1").style.backgroundColor="pink";
}
function test2() {
document.getElementById("1").style.backgroundColor="white";
}
script>
body>
<style>img {
padding: 20px;}
style>
<body>
<div>
<img src="../imgs/126.jpg" onclick="dan()" onmouseout="out(this)" onmouseover="over(this)">
<img src="../imgs/126.jpg" ondblclick="shuang()" onmouseout="out(this)" onmouseover="over(this)">
div>
<script>
function dan() {
alert("单击了一下");
}
function shuang() {
alert("双击了一下");
}
function over(img) {
img.style.border = "pink 5px solid";
}
function out(img) {
img.style.border = "white 5px solid";
}
script>
body>
<script>
window.onkeydown=function () {
//event事件源;keyCode事件编码
console.log("按下去了!"+event.keyCode);
}
window.onkeyup=function () {
console.log("松手了!"+event.keyCode);
}
script>
<body>
<div id="father">
<div id="son">
div>
div>
<script>
document.getElementById("father").addEventListener("click",function () {
alert("父级div被触发"+this.id);
});
document.getElementById("son").addEventListener("click",function (e) {
//e.stopPropagation();取消冒泡机制
alert("子级div被触发"+this.id);
});
script>
从外到内。在冒泡的基础上加个true:
<script>
document.getElementById("father").addEventListener("click",function () {
alert("父级div被触发"+this.id);
},true);
document.getElementById("son").addEventListener("click",function (e) {
alert("子级div被触发"+this.id);
},true);
script>
<script>
//方式一:使用Object创建
var user=new Object();
user.name="zoe";
user.age=18;
user.say=function () {
console.log("大家好,我是"+user.name+"!");
}
user.say();//大家好,我是zoe!
//方式二:使用构造函数
function strUser(name,age) {
this.name=name;
this.age=age;
this.say=function () {
//this 的值,在函数中使用时,是“拥有”该函数的对象。
console.log("大家好,我是"+this.name+"!");
}
}
var user=new strUser("EZ",18);
user.say();//大家好,我是EZ!
//使用直接量
var dog={
name:"husky",
age:6,
say:function () {
console.log("我是"+this.name);//我是husky
}
}
dog.say();
script>
<script>
var json1 = {
name: "zoe", age: 18}
console.log(json1);//Object
console.log(json1.name + json1.age);//zoe18
//json数组
var jsons =[
{
name: "zoe", age: 18, hobby: ["Q", "W", "E"]},
{
name: "ez", age: 18, hobby: ["Q", "W", "E"]}
];
console.log(jsons[1].name + jsons[1].age + jsons[1].hobby[1]);
//ez18w
script>
<body>
<button onclick="test()">百度button>
<script>
function test() {
//url地址+新窗口的名称+可选窗口的特征
window.open("http://www.baidu.com","baidu","width=200,height=200,left=200");
}
script>
body>
<body>
<button onclick="test()">获取屏幕分辨率button>
<script>
function test() {
console.log(window.screen.width+" "+window.screen.height)//1920*1080
}
script>
<script>
function test() {
console.log(location.href);//url信息
location.reload();//刷新
location.href = "http://www.baidu.com";//跳转页面
}
script>
<body>
<a href="b.html">去b页面a>
body>
<body>
<button onclick="test()">返回button>
<script>
function test() {
//history.back();等价
history.go(-1);
}
script>
body>
<script>
var str = "";
str += "浏览器的代号:"
+ navigator.appCodeName +"";
str += "浏览器的名称:"
+ navigator.appName+"";
str += "浏览器的版本:"
+ navigator.appVersion+"";
str += "硬件平台:"
+ navigator.platform+"";
str += "用户代理:"
+ navigator.userAgent +"";
str += "启用Cookies:"
+navigator.cookieEnabled+"";
document.write(str);
script>
<script>
//保存数据setItem()
localStorage.setItem("name","张三");
//提取数据getItem()
console.log( localStorage.getItem("name"));//张三
//删除数据removeItem()
localStorage.removeItem("name")
console.log( localStorage.getItem("name"));//null
//其他保存方式:
localStorage["a"] = 1;
localStorage.b = 2;
script>
<body>
<button onclick="dian()">点我button>
<button onclick="del()">点我清空button>
<h3 id="result">h3>
<script>
function dian(){
if( sessionStorage.getItem("clickCount") ){
sessionStorage.setItem("clickCount",
//对象的值转换为数字,否则会变成1111字符串形式
Number(sessionStorage.getItem("clickCount")) + 1);
}else{
sessionStorage.setItem("clickCount", 1);
}
document.getElementById("result").innerHTML = "已经点击了"+
sessionStorage.getItem("clickCount") +"次!"
}
function del() {
sessionStorage.clear();
document.getElementById("result").innerHTML ="";
}
script>
body>
setInterval(函数,时间周期(毫秒)):
案例:字体变色
<body>
<h1 id="h1">Zoe!h1>
<script>
var colors=["pink","red","yellw","blue"];
var i=0;
setInterval(bian,200);
function bian() {
document.getElementById("h1").style.color=colors[i++];
if (i==colors.length){
i=0;
}
}
//实现电子时钟,只需加一个定时器每1000ms执行一次,在函数内部定义日期对象,给外部标签赋值。
script>
body>
clearInterval(定时器对象)
案例:照片依次播放,点击停止
<body>
<img id="tu" src="../imgs/早坂爱.png" width="30%" height="300">
<br>
<button onclick="begin()">开始button>
<button onclick="stop()">停止button>
<script>
var imgs=["hudei.jpg","psc.jpg","zoe.jpg","zoe2.jpg","zoe3.jpg"];
var i=0;
function begin() {
timer=setInterval(bian,300);
}
function stop() {
clearInterval(timer);
}
function bian() {
//var i=Math.floor(Math.random()*imgs.length); //0-4
if (i == imgs.length - 1) {
//到达最后一张图,赋值后,i归零
document.getElementById("tu").src = "../imgs/" + imgs[i];
i = 0;
} else {
document.getElementById("tu").src = "../imgs/" + imgs[i++];
}
}
script>
body>
<body>
<div id="d1" style="background-color: pink ;width: 300px;height: 300px">div>
<script>
function bian() {
document.getElementById("d1").style.backgroundColor="blue";
}
setTimeout(bian,3000);
script>
body>