JavaScript 基础知识
JavaScript 是一种为你的网站添加交互性的编程语言。这种情况发生在游戏中、按下按钮或在表单上输入数据时的响应行为中;具有动感的样式;动画等。本文帮助你开始使用 JavaScript 并加深你对可能性的理解。
¥JavaScript is a programming language that adds interactivity to your website. This happens in games, in the behavior of responses when buttons are pressed or with data entry on forms; with dynamic styling; with animation, etc. This article helps you get started with JavaScript and furthers your understanding of what is possible.
什么是 JavaScript?
¥What is JavaScript?
JavaScript 是一种功能强大的编程语言,可以为网站添加交互性。它是由布伦丹·艾希发明的。
¥JavaScript is a powerful programming language that can add interactivity to a website. It was invented by Brendan Eich.
JavaScript 用途广泛且适合初学者。有了更多的经验,你将能够创建游戏、动画 2D 和 3D 图形、全面的数据库驱动应用等等!
¥JavaScript is versatile and beginner-friendly. With more experience, you'll be able to create games, animated 2D and 3D graphics, comprehensive database-driven apps, and much more!
JavaScript 本身相对紧凑,但非常灵活。开发者在核心 JavaScript 语言之上编写了各种工具,以最小的努力解锁了大量的功能。这些包括:
¥JavaScript itself is relatively compact, yet very flexible. Developers have written a variety of tools on top of the core JavaScript language, unlocking a vast amount of functionality with minimum effort. These include:
- 浏览器应用编程接口(APIs)内置于网络浏览器中,提供动态创建 HTML 和设置 CSS 样式等功能;收集和操作来自用户网络摄像头的视频流,或生成 3D 图形和音频样本。
- 第三方 API 允许开发者将功能合并到其他内容提供商(例如 讨论 或 Facebook)的网站中。
- 可应用于 HTML 的第三方框架和库,以加速构建网站和应用的工作。
介绍核心 JavaScript 语言与上面列出的工具有何不同的详细信息超出了本文的范围(作为 JavaScript 的简要介绍)。你可以在 MDN 的 JavaScript 学习区 以及 MDN 的其他部分了解更多信息。
¥It's outside the scope of this article—as a light introduction to JavaScript—to present the details of how the core JavaScript language is different from the tools listed above. You can learn more in MDN's JavaScript learning area, as well as in other parts of MDN.
下面的部分介绍了核心语言的一些方面,并提供了使用一些浏览器 API 功能的机会。玩得开心!
¥The section below introduces some aspects of the core language and offers an opportunity to play with a few browser API features too. Have fun!
"你好世界!" 示例
¥A "Hello world!" example
JavaScript 是最流行的现代网络技术之一!随着你的 JavaScript 技能的增长,你的网站将进入一个新的力量和创造力维度。
¥JavaScript is one of the most popular modern web technologies! As your JavaScript skills grow, your websites will enter a new dimension of power and creativity.
然而,熟悉 JavaScript 比熟悉 HTML 和 CSS 更具挑战性。你可能必须从小处开始,逐步进步。首先,我们来看看如何将 JavaScript 添加到页面以创建 Hello world!例子。(你好世界!是 入门编程示例的标准。)
¥However, getting comfortable with JavaScript is more challenging than getting comfortable with HTML and CSS. You may have to start small, and progress gradually. To begin, let's examine how to add JavaScript to your page for creating a Hello world! example. (Hello world! is the standard for introductory programming examples.)
警告:如果你还没有跟上我们课程的其余部分,请阅读 下载此示例代码 并将其作为起点。
¥Warning: If you haven't been following along with the rest of our course, download this example code and use it as a starting point.
- 转到你的测试站点并创建一个名为
scripts
的新文件夹。在脚本文件夹中,创建一个名为main.js
的新文本文档并保存。 - 在
index.html
文件中,在新行中的</body>
结束标记之前输入以下代码:html<script src="scripts/main.js"></script>
- 这与 CSS 的
<link>
元素执行相同的工作。它将 JavaScript 应用到页面,因此它可以对 HTML(以及 CSS 以及页面上的其他任何内容)产生影响。 - 将此代码添加到
main.js
文件中:jsconst myHeading = document.querySelector("h1"); myHeading.textContent = "Hello world!";
- 确保 HTML 和 JavaScript 文件已保存。然后在浏览器中加载
index.html
。你应该看到这样的东西:
注意:上述说明将
<script>
元素放置在 HTML 文件底部附近的原因是浏览器按照代码在文件中出现的顺序读取代码。¥Note: The reason the instructions (above) place the
<script>
element near the bottom of the HTML file is that the browser reads code in the order it appears in the file.如果 JavaScript 首先加载并且它应该影响尚未加载的 HTML,则可能会出现问题。将 JavaScript 放置在 HTML 页面底部附近是适应这种依赖的一种方法。要了解有关替代方法的更多信息,请参阅 脚本加载策略。
¥If the JavaScript loads first and it is supposed to affect the HTML that hasn't loaded yet, there could be problems. Placing JavaScript near the bottom of an HTML page is one way to accommodate this dependency. To learn more about alternative approaches, see Script loading strategies.
发生了什么?
¥What happened?
标题文本更改为 Hello world!使用 JavaScript。你通过使用名为 querySelector()
的函数来获取对标题的引用,然后将其存储在名为 myHeading
的变量中来完成此操作。这与我们使用 CSS 选择器所做的类似。当你想对某个元素执行某些操作时,需要先选择它。
¥The heading text changed to Hello world! using JavaScript. You did this by using a function called querySelector()
to grab a reference to your heading, and then store it in a variable called myHeading
. This is similar to what we did using CSS selectors. When you want to do something to an element, you need to select it first.
接下来,代码将 myHeading
变量的 textContent
属性(表示标题的内容)的值设置为 Hello world!。
¥Following that, the code set the value of the myHeading
variable's textContent
property (which represents the content of the heading) to Hello world!.
注意:你在本练习中使用的两个功能都是 文档对象模型 (DOM) API 的一部分,文档对象模型 (DOM) API 具有操作文档的能力。
¥Note: Both of the features you used in this exercise are parts of the Document Object Model (DOM) API, which has the capability to manipulate documents.
语言基础速成课程
¥Language basics crash course
为了让你更好地理解 JavaScript 的工作原理,我们来解释一下该语言的一些核心功能。值得注意的是,这些功能对于所有编程语言都是通用的。如果你掌握了这些基础知识,那么你在使用其他语言进行编码时也将处于领先地位!
¥To give you a better understanding of how JavaScript works, let's explain some of the core features of the language. It's worth noting that these features are common to all programming languages. If you master these fundamentals, you have a head start on coding in other languages too!
警告:在本文中,尝试将示例代码行输入 JavaScript 控制台,看看会发生什么。有关 JavaScript 控制台的更多详细信息,请参阅 探索浏览器开发者工具。
¥Warning: In this article, try entering the example code lines into your JavaScript console to see what happens. For more details on JavaScript consoles, see Discover browser developer tools.
变量
¥Variables
Variables 是存储值的容器。首先使用 let
关键字声明一个变量,后跟你为该变量指定的名称:
¥Variables are containers that store values. You start by declaring a variable with the let
keyword, followed by the name you give to the variable:
let myVariable;
行尾的分号表示语句的结束位置。仅当你需要将语句分隔在一行上时才需要它。然而,有些人认为在每个语句末尾添加分号是一种很好的做法。对于何时应该和不应该使用分号还有其他规则。详细信息请参见 JavaScript 分号指南。
¥A semicolon at the end of a line indicates where a statement ends. It is only required when you need to separate statements on a single line. However, some people believe it's good practice to have semicolons at the end of each statement. There are other rules for when you should and shouldn't use semicolons. For more details, see Your Guide to Semicolons in JavaScript.
你几乎可以为变量命名任何名称,但有一些限制。(见 本节介绍命名规则。)如果你不确定,你可以 检查你的变量名 看看它是否有效。
¥You can name a variable nearly anything, but there are some restrictions. (See this section about naming rules.) If you are unsure, you can check your variable name to see if it's valid.
JavaScript 区分大小写。这意味着 myVariable
与 myvariable
不同。如果你的代码有问题,请检查案例!
¥JavaScript is case sensitive. This means myVariable
is not the same as myvariable
. If you have problems in your code, check the case!
声明变量后,你可以给它赋值:
¥After declaring a variable, you can give it a value:
myVariable = "Bob";
此外,你可以在同一行执行这两个操作:
¥Also, you can do both these operations on the same line:
let myVariable = "Bob";
你可以通过调用变量名称来检索值:
¥You retrieve the value by calling the variable name:
myVariable;
为变量赋值后,你可以稍后在代码中更改它:
¥After assigning a value to a variable, you can change it later in the code:
let myVariable = "Bob";
myVariable = "Steve";
请注意,变量可能保存具有不同 数据类型 的值:
¥Note that variables may hold values that have different data types:
多变的 | 解释 | 示例 |
---|---|---|
String | 这是称为字符串的文本序列。要表示该值是字符串,请将其括在单引号或双引号中。 | let myVariable = 'Bob'; 或let myVariable = "Bob"; |
Number | 这是一个数字。数字周围没有引号。 | let myVariable = 10; |
Boolean |
这是一个 True/False 值。 true 和
false 是不需要引号的特殊关键字。
|
let myVariable = true; |
Array | 这是一个允许你在单个引用中存储多个值的结构。 |
let myVariable = [1,'Bob','Steve',10]; 像这样引用数组的每个成员: myVariable[0] 、
myVariable[1] 等。
|
Object | 这可以是任何东西。JavaScript 中的一切都是对象,并且可以存储在变量中。学习时请记住这一点。 | let myVariable = document.querySelector('h1'); 上面的例子也是如此。 |
那么为什么我们需要变量呢?在编程中做任何有趣的事情都需要变量。如果值无法更改,那么你就无法执行任何动态操作,例如个性化问候消息或更改图片库中显示的图片。
¥So why do we need variables? Variables are necessary to do anything interesting in programming. If values couldn't change, then you couldn't do anything dynamic, like personalize a greeting message or change an image displayed in an image gallery.
评论
¥Comments
注释是可以与代码一起添加的文本片段。浏览器会忽略标记为注释的文本。你可以像在 CSS 中一样在 JavaScript 中编写注释:
¥Comments are snippets of text that can be added along with code. The browser ignores text marked as comments. You can write comments in JavaScript just as you can in CSS:
/*
Everything in between is a comment.
*/
如果你的注释不包含换行符,可以选择将其放在两个斜杠后面,如下所示:
¥If your comment contains no line breaks, it's an option to put it behind two slashes like this:
// This is a comment
运算符
¥Operators
operator
是一个数学符号,它根据两个值(或变量)生成结果。在下表中,你可以看到一些最简单的运算符,以及在 JavaScript 控制台中尝试的一些示例。
¥An operator
is a mathematical symbol that produces a result based on two values (or variables). In the following table, you can see some of the simplest operators, along with some examples to try in the JavaScript console.
运算符 | 解释 | Symbol(s) | 示例 |
---|---|---|---|
添加 | 将两个数字相加或组合两个字符串。 | + |
XSPACE6 + 9; |
减法、乘法、除法 | 这些功能符合你在基础数学中所期望的功能。 | - , ---STAR--- , / |
XSPACE9 - 3; |
赋值 | 正如你已经看到的:这给变量赋值。 | = |
let myVariable = 'Bob'; |
严格平等 |
这将执行测试以查看两个值是否相等且数据类型相同。它返回
true /false (布尔)结果。
|
=== |
let myVariable = 3; |
不、不等于 | 这将返回与其前面的逻辑相反的值。它将 true 变成 false ,等等。当它与相等运算符一起使用时,否定运算符会测试两个值是否不相等。 |
! , !== |
对于 "不是",基本表达式是
"不相等" 给出了基本相同的结果,但语法不同。这里我们正在测试 "
|
还有很多操作符需要探索,但目前就足够了。完整列表请参见 表达式和运算符。
¥There are a lot more operators to explore, but this is enough for now. See Expressions and operators for a complete list.
注意:执行计算时混合数据类型可能会导致一些奇怪的结果。请注意正确引用变量并获得预期的结果。例如,在控制台中输入
'35' + '25'
。为什么没有得到你期望的结果?因为引号将数字转换为字符串,所以你最终是连接字符串而不是添加数字。如果你输入35 + 25
,你将得到两个数字的总和。¥Note: Mixing data types can lead to some strange results when performing calculations. Be careful that you are referring to your variables correctly, and getting the results you expect. For example, enter
'35' + '25'
into your console. Why don't you get the result you expected? Because the quote marks turn the numbers into strings, so you've ended up concatenating strings rather than adding numbers. If you enter35 + 25
you'll get the total of the two numbers.
条件句
¥Conditionals
条件是用于测试表达式是否返回 true 的代码结构。条件语句的一种非常常见的形式是 if...else
语句。例如:
¥Conditionals are code structures used to test if an expression returns true or not. A very common form of conditionals is the if...else
statement. For example:
let iceCream = "chocolate";
if (iceCream === "chocolate") {
alert("Yay, I love chocolate ice cream!");
} else {
alert("Awwww, but chocolate is my favorite…");
}
if ()
里面的表达式就是测试。这使用严格相等运算符(如上所述)将变量 iceCream
与字符串 chocolate
进行比较,看看两者是否相等。如果此比较返回 true
,则运行第一个代码块。如果比较不正确,则改为运行 else
语句之后的第二个代码块。
¥The expression inside the if ()
is the test. This uses the strict equality operator (as described above) to compare the variable iceCream
with the string chocolate
to see if the two are equal. If this comparison returns true
, the first block of code runs. If the comparison is not true, the second block of code—after the else
statement—runs instead.
函数
¥Functions
Functions 是一种打包你希望重用的功能的方式。可以将代码体定义为函数,当你在代码中调用函数名称时执行该函数。这是重复编写相同代码的一个很好的替代方法。你已经了解了函数的一些用法。例如:
¥Functions are a way of packaging functionality that you wish to reuse. It's possible to define a body of code as a function that executes when you call the function name in your code. This is a good alternative to repeatedly writing the same code. You have already seen some uses of functions. For example:
let myVariable = document.querySelector("h1");
alert("hello!");
这些函数 document.querySelector
和 alert
内置于浏览器中。
¥These functions, document.querySelector
and alert
, are built into the browser.
如果你看到一些看起来像变量名的东西,但后面有括号 - ()
- 它很可能是一个函数。函数通常采用 arguments:他们完成工作所需的数据位。参数放在括号内,如果有多个参数,则用逗号分隔。
¥If you see something which looks like a variable name, but it's followed by parentheses— ()
—it is likely a function. Functions often take arguments: bits of data they need to do their job. Arguments go inside the parentheses, separated by commas if there is more than one argument.
例如,alert()
函数使浏览器窗口中出现一个弹出框,但我们需要给它一个字符串作为参数来告诉函数要显示什么消息。
¥For example, the alert()
function makes a pop-up box appear inside the browser window, but we need to give it a string as an argument to tell the function what message to display.
你还可以定义自己的函数。在下一个示例中,我们创建一个简单的函数,它将两个数字作为参数并将它们相乘:
¥You can also define your own functions. In the next example, we create a simple function which takes two numbers as arguments and multiplies them:
function multiply(num1, num2) {
let result = num1 * num2;
return result;
}
尝试在控制台中运行它;然后用几个参数进行测试。例如:
¥Try running this in the console; then test with several arguments. For example:
multiply(4, 7);
multiply(20, 20);
multiply(0.5, 3);
注意:
return
语句告诉浏览器从函数中返回result
变量,以便可以使用它。这是必要的,因为在函数内部定义的变量仅在这些函数内部可用。这称为变量 scoping。(阅读有关 变量范围 的更多信息。)¥Note: The
return
statement tells the browser to return theresult
variable out of the function so it is available to use. This is necessary because variables defined inside functions are only available inside those functions. This is called variable scoping. (Read more about variable scoping.)
事件
¥Events
网站上的真正交互需要事件处理程序。这些是监听浏览器中的活动并运行代码作为响应的代码结构。最明显的例子是处理 点击事件,当你用鼠标单击某些内容时,浏览器会触发该 点击事件。要演示这一点,请在控制台中输入以下内容,然后单击当前网页:
¥Real interactivity on a website requires event handlers. These are code structures that listen for activity in the browser, and run code in response. The most obvious example is handling the click event, which is fired by the browser when you click on something with your mouse. To demonstrate this, enter the following into your console, then click on the current webpage:
document.querySelector("html").addEventListener("click", function () {
alert("Ouch! Stop poking me!");
});
有多种方法可以将事件处理程序附加到元素。这里我们选择 <html>
元素。然后我们调用它的 addEventListener()
函数,传入要监听的事件名称 ('click'
) 以及事件发生时要运行的函数。
¥There are a number of ways to attach an event handler to an element.
Here we select the <html>
element. We then call its addEventListener()
function, passing in the name of the event to listen to ('click'
) and a function to run when the event happens.
我们刚刚传递给 addEventListener()
的函数被称为匿名函数,因为它没有名称。还有另一种编写匿名函数的方法,我们称之为箭头函数。箭头函数使用 () =>
而不是 function ()
:
¥The function we just passed to addEventListener()
here is called an anonymous function, because it doesn't have a name. There's an alternative way of writing anonymous functions, which we call an arrow function.
An arrow function uses () =>
instead of function ()
:
document.querySelector("html").addEventListener("click", () => {
alert("Ouch! Stop poking me!");
});
增强我们的示例网站
¥Supercharging our example website
完成对 JavaScript 基础知识的回顾(见上文)后,让我们向示例站点添加一些新功能。
¥With this review of JavaScript basics completed (above), let's add some new features to our example site.
在继续之前,删除 main.js
文件的当前内容(你之前在 "你好世界!" 示例中添加的部分)并保存空文件。如果不这样做,现有代码将与你要添加的新代码发生冲突。
¥Before going any further, delete the current contents of your main.js
file — the bit you added earlier during the "Hello world!" example — and save the empty file. If you don't, the existing code will clash with the new code you are about to add.
添加图片转换器
¥Adding an image changer
在本节中,你将学习如何使用 JavaScript 和 DOM API 功能来交替显示两个图片之一。当用户单击显示的图片时,就会发生此更改。
¥In this section, you will learn how to use JavaScript and DOM API features to alternate the display of one of two images. This change will happen as a user clicks the displayed image.
- 选择你想要在示例网站上展示的图片。理想情况下,图片的大小与你之前添加的图片的大小相同或尽可能接近。
- 将此图片保存在
images
文件夹中。 - 将图片重命名为 firefox2.png。
- 将以下 JavaScript 代码添加到你的
main.js
文件中。jsconst myImage = document.querySelector("img"); myImage.onclick = () => { const mySrc = myImage.getAttribute("src"); if (mySrc === "images/firefox-icon.png") { myImage.setAttribute("src", "images/firefox2.png"); } else { myImage.setAttribute("src", "images/firefox-icon.png"); } };
- 保存所有文件并在浏览器中加载
index.html
。现在,当你单击该图片时,它应该更改为另一张图片。
这就是发生的事情。你在 myImage
中存储了对 <img>
元素的引用。接下来,你将其 onclick
事件处理程序属性设置为等于一个没有名称的函数("anonymous" 函数)。所以每次点击这个元素时:
¥This is what happened. You stored a reference to your <img>
element in myImage
. Next, you made its onclick
event handler property equal to a function with no name (an "anonymous" function). So every time this element is clicked:
- 该代码检索图片的
src
属性的值。 - 该代码使用条件来检查
src
值是否等于原始图片的路径:- 如果是,代码会将
src
值更改为第二个图片的路径,强制将另一个图片加载到<img>
元素内。 - 如果不是(意味着它必须已经更改),则
src
值将交换回原始图片路径,即原始状态。
- 如果是,代码会将
添加个性化欢迎信息
¥Adding a personalized welcome message
接下来,让我们将页面标题更改为用户首次访问该网站时的个性化欢迎消息。此欢迎信息将持续存在。如果用户离开网站并稍后返回,我们将使用 Web 存储 API。我们还将包含一个更改用户的选项,以及因此的欢迎消息。
¥Next, let's change the page title to a personalized welcome message when the user first visits the site. This welcome message will persist. Should the user leave the site and return later, we will save the message using the Web Storage API. We will also include an option to change the user, and therefore, the welcome message.
- 在
index.html
中,在<script>
元素之前添加以下行:html<button>Change user</button>
- 在
main.js
中,将以下代码放置在文件底部,与编写的完全相同。这需要引用新按钮和标题,存储每个内部变量:jslet myButton = document.querySelector("button"); let myHeading = document.querySelector("h1");
- 添加以下函数来设置个性化问候语。这还不会起任何作用,但很快就会改变。
js
function setUserName() { const myName = prompt("Please enter your name."); localStorage.setItem("name", myName); myHeading.textContent = `Mozilla is cool, ${myName}`; }
setUserName()
函数包含prompt()
函数,该函数显示一个对话框,与alert()
类似。这个prompt()
函数比alert()
做了更多的事情,要求用户输入数据,并在用户单击“确定”后将其存储在变量中。在本例中,我们要求用户输入名称。接下来,代码调用 APIlocalStorage
,它允许我们在浏览器中存储数据并在以后检索它。我们使用 localStorage 的setItem()
函数创建并存储名为'name'
的数据项,并将其值设置为myName
变量,该变量包含用户输入的名称。最后,我们将标题的textContent
设置为字符串,加上用户新存储的名称。 - 在函数声明后添加以下条件块。我们可以调用此初始化代码,因为它在首次加载时构建应用。
该块的第一行使用否定运算符(逻辑 NOT,由js
if (!localStorage.getItem("name")) { setUserName(); } else { const storedName = localStorage.getItem("name"); myHeading.textContent = `Mozilla is cool, ${storedName}`; }
!
表示)来检查name
数据是否存在。如果没有,则运行setUserName()
函数来创建它。如果存在(即用户在上次访问期间设置了用户名),我们使用getItem()
检索存储的名称,并将标题的textContent
设置为字符串,加上用户名,就像我们在setUserName()
中所做的那样。 - 将此
onclick
事件处理程序(如下)放在按钮上。单击后,setUserName()
运行。这允许用户通过按按钮输入不同的名称。jsmyButton.onclick = () => { setUserName(); };
用户名为空?
¥A user name of null?
当你运行该示例并出现提示你输入用户名的对话框时,请尝试按“取消”按钮。你最终的标题应该是 Mozilla is Cool, null。发生这种情况的原因是,当你取消提示时,该值被设置为 null
。Null 是 JavaScript 中的一个特殊值,表示没有值。
¥When you run the example and get the dialog box that prompts you to enter your user name, try pressing the Cancel button. You should end up with a title that reads Mozilla is cool, null. This happens because—when you cancel the prompt—the value is set as null
. Null is a special value in JavaScript that refers to the absence of a value.
另外,尝试单击“确定”而不输入名称。出于相当明显的原因,你最终应该得到一个标题,上面写着“Mozilla 很酷”。
¥Also, try clicking OK without entering a name. You should end up with a title that reads Mozilla is cool, for fairly obvious reasons.
为了避免这些问题,你可以检查用户是否没有输入空白名称。将你的 setUserName()
函数更新为:
¥To avoid these problems, you could check that the user hasn't entered a blank name. Update your setUserName()
function to this:
function setUserName() {
const myName = prompt("Please enter your name.");
if (!myName) {
setUserName();
} else {
localStorage.setItem("name", myName);
myHeading.textContent = `Mozilla is cool, ${myName}`;
}
}
在人类语言中,这意味着:如果 myName
没有值,则从头开始再次运行 setUserName()
。如果它确实有值(如果上述语句不成立),则将该值存储在 localStorage
中并将其设置为标题的文本。
¥In human language, this means: If myName
has no value, run setUserName()
again from the start. If it does have a value (if the above statement is not true), then store the value in localStorage
and set it as the heading's text.
结论
¥Conclusion
如果你已按照本文中的所有说明进行操作,你最终应该会看到如下图所示的页面。你也可以 查看我们的版本。
¥If you have followed all the instructions in this article, you should end up with a page that looks something like the image below. You can also view our version.
如果你遇到困难,你可以将你的工作与我们的 GitHub 上完成的示例代码 进行比较。
¥If you get stuck, you can compare your work with our finished example code on GitHub.
我们刚刚触及了 JavaScript 的皮毛。如果你喜欢玩游戏并希望更进一步,请利用下面列出的资源。
¥We have just scratched the surface of JavaScript. If you enjoyed playing, and wish to go further, take advantage of the resources listed below.
也可以看看
¥See also
- 使用 JavaScript 进行动态客户端脚本编写
-
更详细地深入研究 JavaScript。
- 学习 JavaScript
-
对于有抱负的 Web 开发者来说,这是一个极好的资源!在自动化评估的指导下,通过简短的课程和交互式测试,在交互式环境中学习 JavaScript。前 40 节课免费。只需一次性支付少量费用即可获得完整的课程。