JavaScript-模板

JavaScript-模板

2021-02-20

基础

直接写入 HTML 输出流

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>W3Cschool教程(w3cschool.cn)</title>
</head>

<body>

    <p>JavaScript 能够直接写入 HTML 输出流中:</p>
    <script>
        document.write("<h1>这是一个标题</h1>");
        document.write("<p>这是一个段落。</p>");
    </script>
    <p>
        您只能在 HTML 输出流中使用 <strong>document.write</strong>。
        如果您在文档已加载后使用它(比如在函数中),会覆盖整个文档。
    </p>

</body>

</html>

image-20210216204717281

对事件的反应

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>W3Cschool教程(w3cschool.cn)</title>
</head>

<body>

    <h1>我的第一个 JavaScript</h1>
    <p>
        JavaScript 能够对事件作出反应。比如对按钮的点击:
    </p>
    <button type="button" onclick="alert('欢迎!')">点我!</button>

</body>

</html>

image-20210216204824769

改变 HTML 内容

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>W3Cschool教程(w3cschool.cn)</title>
</head>

<body>

    <h1>我的第一段 JavaScript</h1>
    <p id="demo">
        JavaScript 能改变 HTML 元素的内容。
    </p>
    <script>
        function myFunction() {
     
     
            x = document.getElementById("demo"); // 找到元素
            x.innerHTML = "Hello JavaScript!"; // 改变内容
        }
    </script>
    <button type="button" onclick="myFunction()">点击这里</button>

</body>

</html>

改变 HTML 图像

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>W3Cschool教程(w3cschool.cn)</title>
</head>

<body>

    <script>
        function changeImage() {
     
     
            element = document.getElementById('myimage')
            if (element.src.match("bulbon")) {
     
     
                element.src = "/statics/images/course/pic_bulboff.gif";
            } else {
     
     
                element.src = "/statics/images/course/pic_bulbon.gif";
            }
        }
    </script>
    <img id="myimage" onclick="changeImage()" src="/statics/images/course/pic_bulboff.gif" width="100" height="180">
    <p>点击灯泡就可以打开或关闭这盏灯</p>

</body>

</html>

改变 HTML 样式

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>W3Cschool教程(w3cschool.cn)</title>
</head>

<body>
    <h1>我的第一段 JavaScript</h1>
    <p id="demo">
        JavaScript 能改变 HTML 元素的样式。
    </p>
    <script>
        function myFunction() {
     
     
            x = document.getElementById("demo") // 找到元素
            x.style.color = "#ff0000"; // 改变样式
        }
    </script>
    <button type="button" onclick="myFunction()">点击这里</button>
</body>

</html>

验证输入

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>W3Cschool教程(w3cschool.cn)</title>
</head>

<body>

    <h1>我的第一段 JavaScript</h1>
    <p>请输入数字。如果输入值不是数字,浏览器会弹出提示框。</p>
    <input id="demo" type="text">
    <script>
        function myFunction() {
     
     
            var x = document.getElementById("demo").value;
            if (x == "" || isNaN(x)) {
     
     
                alert("不是数字");
            }
        }
    </script>
    <button type="button" onclick="myFunction()">点击这里</button>

</body>

</html>

image-20210216205119338

用法

放的位置

HTML 中的脚本必须位于 <script> 与 </script> 标签之间。

head中的 JavaScript 函数

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>W3Cschool教程(w3cschool.cn)</title>
    <script>
        function myFunction() {
     
     
            document.getElementById("demo").innerHTML = "我的第一个 JavaScript 函数";
        }
    </script>
</head>

<body>

    <h1>我的 Web 页面</h1>
    <p id="demo">一个段落。</p>
    <button type="button" onclick="myFunction()">点击这里</button>

</body>

</html>

body 中的 JavaScript 函数

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>W3Cschool教程(w3cschool.cn)</title>
</head>

<body>

    <h1>我的第一个 Web 页面</h1>
    <p id="demo">一个段落。</p>
    <button type="button" onclick="myFunction()">点击这里</button>
    <script>
        function myFunction() {
     
     
            document.getElementById("demo").innerHTML = "我的第一个 JavaScript 函数";
        }
    </script>

</body>

</html>

外部的 JavaScript

  • 外部的 JavaScript.html
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>W3Cschool教程(w3cschool.cn)</title>
</head>

<body>

    <h1>我的 Web 页面</h1>
    <p id="demo">一个段落。</p>
    <button type="button" onclick="myFunction()">点击这里</button>
    <p><b>注释:</b>myFunction 保存在名为 "myscript.js" 的外部文件中。</p>
    <script src="myscript.js"></script>

</body>

</html>
  • myscript.js
function myFunction() {
    
    
    document.getElementById("demo").innerHTML = "我的第一个 JavaScript 函数";
}

输出

  • 使用 window.alert() 弹出警告框。
  • 使用 document.write() 方法将内容写到 HTML 文档中。
  • 使用 innerHTML 写入到 HTML 元素。
  • 使用 console.log() 写入到浏览器的控制台。

window.alert()

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>W3Cschool教程(w3cschool.cn)</title>
</head>

<body>

    <h1>我的第一个页面</h1>
    <p>我的第一个段落。</p>
    <script>
        window.alert(5 + 6);
    </script>

</body>

</html>

操作HTML元素

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>W3Cschool教程(w3cschool.cn)</title>
</head>

<body>

    <h1>我的第一个 Web 页面</h1>
    <p id="demo">我的第一个段落。</p>
    <script>
        // 延时函数 1 s 
        function sleep(d) {
     
     
            for (var t = Date.now(); Date.now() - t <= d;);
        }
        sleep(1000);

        document.getElementById("demo").innerHTML = "段落已修改。";
    </script>

</body>

</html>

写到 HTML 文档

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>W3Cschool教程(w3cschool.cn)</title>
</head>

<body>

    <h1>我的第一个 Web 页面</h1>
    <p>我的第一个段落。</p>
    <script>
        document.write(Date());
        document.write("<h2> 第二段</h2>");
    </script>

</body>

</html>

如果在文档已完成加载后执行 document.write,整个 HTML 页面将被覆盖。

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>W3Cschool教程(w3cschool.cn)</title>
</head>

<body>

    <h1>我的第一个 Web 页面</h1>
    <p>我的第一个段落。</p>
    <button onclick="myFunction()">点我</button>
    <script>
        function myFunction() {
     
     
            document.write(Date());
        }
    </script>

</body>

</html>

控制台输出

console.log(3 + 4);

image-20210216210832363

语法

字面量

// 数字
3.14
1001
123e5

// 字符串
"John Doe"
'John Doe'

// 表达式
5 + 6

// 数组
[1, 2, 3, 4]

// 对象
{
    
    
    firstName: "John",
    lastName: "Doe",
    age: 50,
    eyeColor: "blue"
}

// 函数
function myFunction(a, b) {
    
    
    return a * b;
}

变量

// 没有数据类型的
var x, length;
x = 5;
length = 6;

操作符

(5 + 6) * 10;

标识符

必须以字母、下划线(_)或美元符($)开始

保留字

abstract else instanceof super
boolean enum int switch
break export interface synchronized
byte extends let this
case false long throw
catch final native throws
char finally new transient
class float null true
const for package try
continue function private typeof
debugger goto protected var
default if public void
delete implements return volatile
do import short while
double in static with

注释

// 注释的内容

/*

多行注释
*/

数据类型

var length = 16;
var x = true, y = false;
var points = x * 10;
var lastName = "lim";
var cars = ["1", '2', '3'];
var person = {
    
    
    firstName : "John",
    lastName : "Doe"
};

函数

function myFunction(a, b) {
    
    
    return a * b;                                // 返回 a 乘于 b 的结果
}

function print_data(name, job) {
    
    
    alert("Welcome" + name + ", the" + job);
}

数组

// 1.
var cars = new Array();
cars[0] = "saab";
cars[1] = 'BMW';
// 2. 
var cars = new Array("Saab", 'BWM');
// 3.
var cars = ['Saab', 'BMW'];


作用域

// 此处可调用 carName 全局变量

function myFunction() {
    
    
    // 此处可调用 carName 变量 局部变量
    carName = "Volvo";

    

}

字符串

var carname = "Volvo XC70";

// 取某个
var ch = carname[7];

// 字符串长度
var len = carname.length;

// 索引
var ch = carname.charAt(7);

// 拼接字符串
var str1 = "123";
str1.concat("456");
// "123456"

// 返回字符串中检索指定字符第一次出现的位置
str.indexOf()

// 返回字符串中检索指定字符最后一次出现的位置
str.lastIndexOf()

// 替换与正则表达式匹配的子串
str.replace()
str1.replace("3", "1")

// 找到一个或多个正则表达式的匹配
str.match()

// 提取字符串的片断,并在新的字符串中返回被提取的部分
str1 = "1234";
str1.slice("2")
// "34"

// 	把字符串分割为子字符串数组
str.split()	

// 提取字串
str.substr()

// 返回字符串对象值
toString()

// 返回某个字符串对象的原始值

valueOf()

语句

if else

if (x == 2) {
    
    
    // 
} else if {
    
    
    
} else {
    
    
    
}

switch

var day = new Date().getDay();
switch (day) {
    
    
    case 0 : x = 1; break;
    case 1 : x = 2; break;
    default : x = 2; break;
}

for

for (var i = 0; i < cars.length; ++i) {
    
    
    document.write(cars[i] + '<br>');
}

while

while (i < 5) {
    
    
    x = x + "2";
}

break continue

for (var i = 0; i < 10; ++i) {
    
    
    if (i % 2 == 0) {
    
    
        break;
    } else {
    
    
        continue;
    }
}

错误处理

function message() {
    
    
    try {
    
    
        adddlert("Welcome guest!");
    } catch (err) {
    
    
        txt = "本页有一个错误。\n\n";
        txt += "错误描述:" + err.message + "\n\n";
        txt += "点击确定继续。\n\n";
        alert(txt);
    }
}
function myFunction() {
    
    
    try {
    
    
        var x = document.getElementById("demo").value;
        if (x == "") throw "empty";
        if (isNaN(x)) throw "not a number";
        if (x > 10) throw "too high";
        if (x < 5) throw "too low";
    } catch (err) {
    
    
        var y = document.getElementById("mess");
        y.innerHTML = "Error: " + err + ".";
    }
}

类型转换

查看

typeof "John"                 // 返回 string
typeof 3.14                   // 返回 number
typeof NaN                    // 返回 number
typeof false                  // 返回 boolean
typeof [ 1,2,3,4]              // 返回 object
typeof {
    
    name: 'John', age:34}  // 返回 object
typeof new Date()             // 返回 object
typeof function () {
    
    }         // 返回 function
typeof myCar                  // 返回 undefined (if myCar is not declared)
typeof null                   // 返回 object

返回所有 JavaScript 变量的构造函数

"John".constructor                 // 返回函数 String()  { [native code] }
(3.14).constructor                 // 返回函数 Number()  { [native code] }
false.constructor                  // 返回函数 Boolean() { [native code] }
[1,2, 3,4].constructor              // 返回函数 Array()   { [native code] }
{
    
    name:'John', age:34}.constructor  // 返回函数 Object()  { [native code] }
new Date().constructor             // 返回函数 Date()    { [native code] }
function() {
    
    }.constructor         // 返回函数 Function(){ [native code] }

类型转换

// 1. 将数字转换为字符串
String(123);
(123).toString()

// 2.将字符串转换为数字
Number("3.14")    // 返回 3.14


正则表达式

search

var str = "Visit w3cschool";
var n = str.search(/w3cschool/i);

var str = "Visit w3cschool!";
var n = str.search("w3cschool");

replace

var str = "Visit Microsoft!";
var res = str.replace(/microsoft/i, "w3cschool");

其他

javascript:void(0)

当用户点击以后不会发生任何事

<a href="javascript:void(0)">单击此处什么也不会发生</a>

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>W3Cschool教程(w3cschool.cn)</title>
</head>

<body>
    <p>点击以下链接查看不同效果:</p>
    <a href="javascript:void(0);">点我没有反应的!</a>
    <br>
    <a href="#pos">点我定位到指定位置!</a>
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
    <p id="pos">尾部定位点</p>
</body>

</html>

JavaScript 代码规范

变量名

驼峰法

firstName = "John";
lastName = "Doe";

price = 19.90;
tax = 0.20;

fullPrice = price + (price * tax);

必要空格

var x = y + z;
var values = ["Volvo", "Saab", "Fiat"];

语句

if (time < 20) {
    
    
    greeting = "Good day";
} else {
    
    
    greeting = "Good evening";
}

函数

函数定义

function functionName(parameters) {
    
            
  // 执行的代码        
}

函数表达式

var x = function (a, b) {
    
    
    return a * b
};
var z = x(4, 3);

HTML DOM

image-20210216215800698

查找 HTML 元素

// 1.通过 id
var x = document.getElementById("intro");

// 2.通过标签名
var x = document.getElementById("main");
var y = x.getElementsByTagName("p");

// 3.通过类名
var x = document.getElementsByClassName("intro");

改变 HTML

// 1.改变 HTML 输出流
document.write(Date());

// 2.改变 HTML 内容
document.getElementById("p1").innerHTML = "New text!";

// 3.改变 HTML 属性
document.getElementById("image").src = "landscape.jpg";


改变 CSS

// 1.改变 HTML 样式
document.getElementById("p2").style.color="blue";

DOM 事件

DOM EventListener

DOM 元素

猜你喜欢

转载自blog.csdn.net/weixin_44179485/article/details/113953280