文章目录

  • 一、 JS基础
    • 1-1 JS事件,改变HTML内容
    • 1-2 js输出与js语法练习
    • 1-3 js对象与函数练习
    • 1-4 JS事件,js跳出语句,字符串,for循环
    • 1-5 js的typeof,null...
    • 1-6 正则表达式
    • 1-7 try...catch
    • 1-8 js严格模式
    • 1-9 JS表单验证
    • 1-10 JSON
      • 1-10-1 json.html
      • 1-10-2 json.json
    • 1-11 js:void和异步编程
    • 1-12 Promise对象

一、 JS基础

1-1 JS事件,改变HTML内容

<!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简介</title>
</head><body><button type="button" onclick="alert('欢迎!')">点我!</button><div id="demo">我电脑设备</div><script>// 直接写入HTML输出流document.write("<h1>这是一个标题</h1>");document.write("<p>这是一个段落。</p>");// 改变HTML内容document.getElementById("demo").innerHTML = "我要好好学web"</script><!-- js改变HTMl图像,动态改变HTML<image>的来源 --><img id="myimage" src="https://www.runoob.com/images/pic_bulboff.gif" onclick="changeImage()" style="display: inline-block; margin:0 200px;" alt=""><script>function changeImage() {element = document.getElementById('myimage')if (element.src.match("bulbon")) {element.src = "https://www.runoob.com/images/pic_bulboff.gif"} else {element.src = "https://www.runoob.com/images/pic_bulbon.gif"}}</script><script>function myfunction() {document.write("使用函数来执行doucment.write,即在文档加载后再执行这个操作,会实现文档覆盖");}document.write("<h1>这是一个标题</h1>");document.write("<p>这是一个段落。</p>");</script><p>您只能在 HTML 输出流中使用 <strong>document.write</strong>。 如果您在文档已加载后使用它(比如在函数中),会覆盖整个文档。</p><button type="button" onclick="myfunction()">点击这里</button></body></html>

1-2 js输出与js语法练习

<!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>2. js 输出</title>
</head><body><!-- js输出 --><h1>我的第一个页面</h1><p>我的第一个段落。</p><button display="block" onclick="myFunction()">文档加载完点我HTML页面会被覆盖</button><script>window.alert(5 + 6);</script><!-- 将javascript直接写在HTML文档中 --><script>document.write(Date())function myFunction() {document.write(Date())}// <!-- js对代码进行拆行 -->document.write("你好 \世界!")//  这根本没用的好吗</script><hr><script>// <!-- js数组 -->var cars = new Array();cars[0] = "Saab";cars[1] = "Vaol";cars[2] = "e";// <!-- 或者 -->var cars = new Array("Saab", "Volvo", "BMW");var cars = ["S", "a", "e"]console.log(cars);</script></body></html>

1-3 js对象与函数练习

<!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对象与函数</title>
</head><body><!-- 访问对象属性 --><p id="demo"></p><script>var person = {firstName: "John",lastName: "Doe",age: 30,fullName() {return this.firstName + " " + this.lastName;}}console.log(person.lastName);console.log(person["lastName"]);document.getElementById("demo").innerHTML = person.fullName()</script><!-- js函数 --><!-- 计算两个数字的乘积,并返回结果 --><div id="demo2"></div><script>function myF(a, b) {return a * b}console.log(myF(2, 3));document.getElementById("demo2").innerHTML = myF(4, 3)</script></body></html>

1-4 JS事件,js跳出语句,字符串,for循环

<!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事件...for循环</title>
</head><body><button onclick="this.innerHTML = Date()">现在的时间是?</button><script>// 字符串也可以是对象var x = "John";// 创建String对象,会拖慢执行速度var y = new String("John");console.log(x);console.log(y);// x是字符串,y是对象console.log(x === y);</script><!-- for循环 --><p id="for_in"></p><script>var txt;var person = {fname: "Bill",lname: "Gates",age: 56};for (x in person) {console.log(person[x]);txt += person[x];}document.getElementById("for_in").innerHTML = txt</script><!-- javaScript标签: 此时break可以用来跳出所有的代码块 --><ul><li id="li"></li></ul><script>cars = ["BMW", "Volvo", "Saab", "Ford"];list: {document.write(cars[0] + "<br>");document.write(cars[1] + "<br>");document.write(cars[2] + "<br>");break list;document.write(cars[3] + "<br>");document.write(cars[4] + "<br>");document.write(cars[5] + "<br>");}for (x in cars) {document.querySelectorById("li").innerHTML = x;}</script></body></html>

1-5 js的typeof,null…

<!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的typeof,null...</title>
</head><body><button onclick="juiceIsDate()">是日日期嘛?</button><p id="demo"></p><script>// null 和 undefined 的值相等,但类型不等:typeof undefined // undefinedtypeof null // objectnull === undefined // falsenull == undefined // true// JS类型转换console.log(typeof NaN); //numberconsole.log(typeof Array); //functionconsole.log(typeof Date);console.log(typeof null); //object//constructor属性console.log("John".constructor);console.log(function() {}.constructor);//使用constructor属性来查看对象是否位日期(包含字符串“Date”)function juiceIsDate() {console.log("调用了");var myDate = new Date();function isDate(myDate) {return myDate.constructor.toString().indexOf("Date") > -1;}document.getElementById("demo").innerHTML = isDate(myDate);}</script>
</body></html>

1-6 正则表达式

<!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>正则表达式</title>
</head><body><script>// search()方法使用正则表达式var str = "Visit Runoob!";var n = str.search(/Run/i);console.log(n);// search()方法使用字符串var str = "Visit Runoob!";var m = str.search("Run")console.log(m);// replace()// test()var patt = /e/var isHere = patt.test("The eeee");/e/.test('HT enjse dzfhje')console.log(isHere);//exec()用于检索字符串中的正则表达式的匹配console.log(/e/.exec("The best Thingse"));</script>
</body></html>

1-7 try…catch

<!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>try catch</title>
</head><body><button onclick=message()>点击查看错误信息</button><script>function message() {try {allert("Welexon");} catch (err) {text = "错误描述:" + err.message + "\n\n";alert(text);}}</script><script>var result = cal(10000);console.log(result);function cal(salary) {// TODO: 在此处补充代码if (salary <= 5000) return 0;else if (salary > 5000 && salary <= 9000) return salary * 0.03;else if (salary > 9000 && salary <= 15000) return salary * 0.05;else return salary * 0.1;}</script><p>不管输入是否正确,输入框都会再输入后清空。</p><p>请输入 5 ~ 10 之间的数字:</p><input id="demo" type="text"><button type="button" onclick="myFunction()">点我</button> ​<div id="p01"></div><!-- finally语句 --><script>function myFunction() {var message, x;message = document.getElementById("p01");message.innerHTML = "";x = document.getElementById("demo").value;try {if (x == "") throw "值是空的";if (isNaN(x)) throw "值不是一个数字";x = Number(x);if (x > 10) throw "太大";if (x < 5) throw "太小";} catch (err) {message.innerHTML = "错误:" + err + ".";} finally {document.getElementById("demo").value = "";}}</script></body></html>

1-8 js严格模式


<!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严格模式</title>
</head><body><script>"use strict";// 不允许使用未声明的变量// myFunction();// function myFunction() {//     y = 3.14;// }var x = 10;var y = "10";if (x === y) {console.log("你好你好");}if (x == y) {console.log("你在干嘛");}</script><script>// 不允许使用未声明的变量myFunction();function myFunction() {y = 3.14;console.log(y);}</script><!-- 解决浮点型数据精确度问题 --><script>var x = 0.1;var y = 0.2;var z = (x * 10 + y * 10) / 10;</script><input type="text" id="getx"><!-- 字符串断行 --><script>var x = "Hello \World!";console.log(x);document.getElementById("getx").value = x;</script>'<!--     数组中使用名字来索引许多程序语言都允许使用名字来作为数组的索引。使用名字来作为索引的数组称为关联数组(或哈希)。JavaScript 不支持使用名字来索引数组,只允许使用数字索引。' --><!-- js使用误区: 应该先使用typeof来检测对象是否已定义 : --><script>if (typeof myObj !== "undedfined" && myObj !== null) {console.log("对象已经定义");}</script>
</body></html>

1-9 JS表单验证

<!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>javascript表单验证</title>
</head><body><!-- 判断fname值是否存在 --><script>function validateForm() {var x = document.forms["myForm"]["fname"].value;if (x == null || x == "") {alert("需要输入名字。");return false;}}</script><form name="myForm" onsubmit="return validateForm()" method="post">名字: <input type="text" name="fname"><input type="button" value="提交"></form></body></html>

1-10 JSON

1-10-1 json.html
<!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>javascript表单验证JSON(js Object Notation)</title>
</head><body><div id="demo"></div><script>var text = '{ "sites" : [' +'{ "name":"Runoob" , "url":"www.runoob.com" },' +'{ "name":"Googlw" , "url":"www.google.com"},' +'{ "name":"Taobao" , "url":"www.taobao.com"}]}';obj = JSON.parse(text);document.getElementById("demo").innerHTML = obj.sites[1].name + " " + obj.sites[1].url;</script></body></html>
1-10-2 json.json
{"sites": [{ "name": "Runam", "url": "www.einm.com" }]
}

1-11 js:void和异步编程

<!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>javascript:void(0)</title>
</head><body><a href="javascript:void(alert('Warning!!'))">点我</a><!-- js异步编程 --><!-- 异步:asynchronous,async --><!-- 同步: synchronous,sync --><div id="demo"></div><script>// function print() {//     document.getElementById("demo").innerHTML = "RUNmmB!";// }// setTimeout(print, 3000);setTimeout(function() {document.getElementById("demo").innerHTML = "ddddfdf";}, 3000);document.getElementById("demo").innerHTML = "RUUM";console.log("2");</script><!-- 异步Ajax --><!-- 除了setTimeout函数以外,XMLHttpRequest常用于请求来自服务器上的XML或JSON数据 --><div id="demo"></div><script>var xhr = new XMLHttpRequest();xhr.onload = function() {document.getElementById("demo").innerHTML = xhr.responseText;}xhr.onerror = function() {document.getElementById("demo").innerHTML = "请求出错!"}// 发送异步GET请求xhr.open("GET", "https://www.runoob.com/try/ajax/ajax_info.txt", true);xhr.send();// jQuery库更加优雅的使用异步AJAX$(document).ready(function() {$("button").click(function() {$.get("", function(data, status) {alert(data, status);});});})</script></body></html>

1-12 Promise对象

<!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>12.Promise对象</title>
</head><body><!-- 格式 --><!-- new Promise(function (resolve, reject){ }) --><script>// setTimeout(function() {//     console.log("First");//     setTimeout(function() {//         console.log("Second");//         setTimeout(function() {//             console.log("Third");//         }, 3000);//     })// })// 用Promise来实现同样的功能new Promise(function(resolve, reject) {setTimeout(function() {console.log("First");resolve();}, 1000)}).then(function() {return new Promise(function(resolve, reject) {setTimeout(function() {console.log("Second");resolve();}, 4000)});}).then(function() {setTimeout(function() {console.log("Third");}, 3000);})new Promise(function(resolve, reject) {console.log("Run");})// resolve表示一切正常,reject是出现异常时所调用的new Promise(function(resolve, reject) {var a = 0;var b = 1;if (b == 0) reject("Dovode zero");else resolve(a / b);}).then(function(value) {console.log("a / b = " + value);}).catch(function(err) {console.log(err);}).finally(function() {console.log("End");})</script><script>// 计时器程序比函数瀑布还要长,将它的核心部分写成一个Promise函数function print(delay, message) {return new Promise(function(resolve, reject) {setTimeout(function() {console.log(message);resolve();}, delay);})}print(1000, "First").then(function() {return print(4000, "Second");}).then(function() {print(3000, "Third");})// 上面可以写的更好看async function asyncFunc() {await print(1000, "First");await print(1000, "two");await print(1000, "three");}// 异步函数在这个Promise原生API的机制是一样的,处理异常的机制将用try-catch块实现async function asyncFunc() {try {await new Promise(function(resolve, reject) {throw "Some error";});} catch (err) {console.log(err);}}asyncFunc();// 如果Promise有一个正常的返回值,await语句也会返回它async function asyncFunc() {let value = await new Promise(function(resolve, reject) {resolve("Return value");});console.log(value);}asyncFunc();</script></body></html>

JS代码练习(上)----cn教程可运行代码相关推荐

  1. python如何运行代码_python上怎么跑(运行)代码

    有朋友刚刚学Python,打开Python之后输入打印hello world的语句之后不知道该咋办了,怎么才能将Python代码跑起来呢?下面我将给大家介绍几种方法. 接下来介绍几种运行python代 ...

  2. php ajaxfileupload.js 使用,ajaxfileupload.js实现文件上传(附步骤代码)

    这次给大家带来ajaxfileupload.js实现文件上传(附步骤代码),ajaxfileupload.js实现文件上传的注意事项有哪些,下面就是实战案例,一起来看一下. AjaxUpLoad.js ...

  3. jtest java 代码_parasoft Jtest 使用教程:检查代码标准

    原标题:parasoft Jtest 使用教程:检查代码标准 通过执行静态分析检查代码是否遵守代码标准的规则,可以识别那些可能会导致功能.性能或安全问题的易于出错和令人困惑的构造. 目的:演示如何检查 ...

  4. php换行太长代码,【PyCharm中文教程 16】代码太长?试试自动换行

    在使用PyCharm码代码的时候,有些单行的代码比较长或者屏幕比较小,经常需要手动拉动滚动条,才能看全代码. 如果不想去动滚动条,其实可以设置超过屏幕宽度的代码自动代码的 点击右键,勾选 Soft-W ...

  5. git 公钥提交代码_gitlab上传公钥和项目代码

    gitlab上传项目需要ssh公钥免交互,本文介绍gitlab设置公钥和上传项目的操作. 一.创建秘钥对 [root@localhost ~]# ssh-keygen -t rsa #一路回车即可 二 ...

  6. 【无标题】把js脚本藏在书签里 一键运行代码

    如果经常针对某网站执行重复的步骤,比如登录.填表.复制内容等操作,可以自定义一段JS脚本,每次只要执行这段脚本代码就能自动完成操作. 但是一般的浏览器直接执行JS脚本并不方便,需要复制粘贴脚本代码,最 ...

  7. 用termux运行python代码_没有电脑?不能运行代码?试试用手机搞定

    今天就来介绍可以在手机和 iPad 上写代码的小工具. iOS 平台:Pythonista Pythonista 自带自动连接,方便移动端敲代码. Pythonista 里面内置一套库,让 Pytho ...

  8. 上过云么?一行代码秒上云体验过么?

    摘要:想要一行代码秒上云,工具自然少不了,这里推荐使用华为云弹性云服务器ECS搭配华为云DevCloud. 年底很多项目都忙着验收回款,验收回款的意义有多重大--成了,项目组发奖金:不成,别说奖金,明 ...

  9. android 运行在ui县城,Android基础:在UI线程中运行代码

    Android基础:在UI线程中运行代码 从在UI线程中运行代码的角度来看,在以下方面有什么区别:MainActivity.this.runOnUiThread(new Runnable() { pu ...

最新文章

  1. typeScript面试必备之-通识七:typeScript中的可索引接口(数组,对象)+类类型接口...
  2. java lambda表达式详解_Java8新特性Lambda表达式详解
  3. django下载excel,使用django-excel插件
  4. 图形结构:遍历模型,分治法,动态规划,回溯法,BFS,DFS
  5. 中石油训练赛 - Racing Gems(最长不下降子序列)
  6. 学用 TStringGrid [1] - ColCount、RowCount、Cells
  7. python的作者叫什么_作者的来历是什么?
  8. 【MySQL】MySQL删除数据库的时候卡死
  9. 搭建一个企业级的Vue工程!
  10. h710阵列卡支持最大硬盘_ORICO推爆品五盘位硬盘柜,一拖五最大支持80TB,你会买吗?...
  11. java中的前加加 和 后加加
  12. 146页智慧政务大数据可视化平台方案
  13. oracle数据库alter table,oracle 数据库 alter table的用法(经典)
  14. 一文详解谷歌最新物联网操作系统 Android Things,话说还记得大明湖畔的Fuchsia吗?
  15. 数字图像处理 第八章 图像压缩
  16. 案例:自动复制黏贴bat
  17. Spring 的第一个Hello Spring
  18. CocosCreator高斯模糊深度优化版
  19. show full processlist,MySQL 优化第7天学习
  20. 【真测有效】VMware 虚拟机上不上网的多种解决方案

热门文章

  1. cf919的ABC(太咸nowatashi)
  2. Unity摄像机控制
  3. 众昂矿业架构师刘金海:氢氟酸原材料依赖萤石
  4. 2023计算机毕业设计SSM最新选题之java全美旅行社网站3ircv
  5. 街上卖什么都不稀罕,但卖这么低贱的草你不觉得奇怪吗?
  6. 【C语言】C 程序开发快速入门
  7. Dart-Aqueduct框架开发(七)
  8. C语言查找指定字符出现的次数,查找子字符串出现的次数,有个bug
  9. [SDOI2018]战略游戏
  10. 南邮计算机专业考什么,南京邮电大学计算机考情分析与经验分享