翻譯不完整。請協助 翻譯此英文文件。
歡迎來到 MDN 的 JavaScript 初學者課程!在這第一個章節中,我們將綜觀 JavaScript ,思考一些問題像是"這是什麼?"和"它的功能是什麼?",確保你了解 JavaScript 的功用。
準備條件: | 有基本的計算機讀寫能力,基本了解 HTML 和 CSS。 |
---|---|
目標: | 為了熟悉 JavaScript 是什麼,它可以做什麼,以及它如何適用於網路站點。 |
高級定義
JavaScript是一種准許您在網頁上實現複雜事物的程式語言 — 每次網頁都比固定在那裡展現靜態資訊給你看做得要多 — 及時顯示內容更新、交互式地圖、繪製2D/3D 動畫圖形以及滾動視訊點唱機等等。— 你會發現 JavaScript 幾乎無處不在。它是標準網路技術的第三層,另外兩個(HTML 和 CSS)我們在學習其他領域的部分已經詳細涵蓋了。
- HTML 是一種標記語言,我們使用它構建和給我們的內容賦予意義, 例如定義段落,標題,數據表格以及在頁面嵌入圖片和視頻等等。.
- CSS 是一種樣式規則的語言,用於在我們的 HTML 內容上應用樣式,例如設置背景顏色、字體以及讓內容多列呈現等等。
- JavaScript 是一種程式語言,它使你能夠創建動態更新內容、控制多媒體,動畫圖片等等幾乎所有事。(好吧,不是所有,但這是非常神奇的僅通過短短幾行 JavaScript 程式碼就可以實現的東西。)
這三層很好的構建在一起。讓我們以一個簡單的文本為例。我們可以使用 HTML 標記來呈現它的結構和意圖:
<p>Player 1: Chris</p>
然後我們可以添加一些樣式混合到一起,獲取更好看的外觀:
p { font-family: 'helvetica neue', helvetica, sans-serif; letter-spacing: 1px; text-transform: uppercase; text-align: center; border: 2px solid rgba(0,0,200,0.6); background: rgba(0,0,200,0.3); color: rgba(0,0,200,0.6); box-shadow: 1px 1px 2px rgba(0,0,200,0.4); border-radius: 10px; padding: 3px 10px; display: inline-block; cursor:pointer; }
最後,我們可以添加一些 JavaScript 來實現動態行為:
var para = document.querySelector('p'); para.addEventListener('click', updateName); function updateName() { var name = prompt('Enter a new name'); para.textContent = 'Player 1: ' + name; }
試試點擊文本看看會發生什麼(注意你同樣可以在 GitHub 找到這個 demo — 查看源程式碼 source code 或 run it live)!
JavaScript 可以做比這些多得多 — 讓我們來更詳細的探索一下。
那麼它究竟可以做什麼呢?
JavaScript 語言的核心包含了很多常用的程式功能供你使用,如:
- 在變數內部存儲有用的值。如上面的例子,我們請求輸入一個新的名字並存儲,那個變數就叫做
name
. - 對文本片段做操作(在程式裡稱作"strings")。在上面的例子裡我們拿了字串 "Player 1: " 並且拼串
name
變數來創建一個完整文本標籤,如:''Player 1: Chris"。 - 執行程式碼響應到確切的事件發生在網頁上。我們在上述例子使用
click
事件偵查,當按鈕被點擊時返回執行更新文本標籤的程式碼。 - 以及其他更多功能!
在JavaScript語言的內核之上還有更多令人激動的功能。也被稱作 應用程式接口(APIs) 它為你使用 JavaScript 程式碼提供了額外強大的支持。
APIs 是以程式碼預先製作完成的模塊,其支援開發者實現較難或無法實現的程式。 他們在編寫程式方面與預先為了建造首頁而製作好的套件做相同的事情 — 拿預先裁切好的板子與螺絲並把他們組合成書架比自己設計、找到合適的木材、裁切成正確的形狀和尺寸、找到合適的螺絲並把他們組合成書架更簡單。
他們通常分為兩類。
Browser APIs( 瀏覽器APIs ) 是被安裝在你的網頁瀏覽器內且可以由本地端的環境中輸出資料或實現複雜的功能。
舉例而言:
- DOM (文件物件模組) API 使你可以操作HTML和CSS,創造、移除和更動 HTML,以新的風格動態的支援你的頁面,等等。每次你看見彈出式視窗展現在網頁上、或一些新的內文展現範例(如同我們曾經在我們簡單的展示中見過的),那就是DOM在做的事。
- Geolocations(地理位置) API 可以讓你取得目前的位置資訊. 這也是 Google Maps 如何取得你的位置並把你的位置標示在地圖上。
- Canvas 及 WebGL APIs 可以讓你在網頁上創造 2D 及 3D 圖像。人們正大量的使用這項技術來創造有趣的產品 — 參見 Chrome Experiments 及 webglsamples.
- Audio and Video APIs ,其中的
HTMLMediaElement
及 WebRTC 可以讓你藉由各種媒體做有趣的事。例如在網頁中播放音樂或影片,又或是使用你的網路攝影機將你的影像在另一個人的網頁上撥放。(可以試著從這個範例 Snapshot demo 了解基本的概念).
Note: 上面列出的範例大多無法在舊版本的瀏覽器上運作 — 當你在嘗試範例時,最好使用 Firefox, Chrome, Edge 或 Opera 來查看運作結果。另外,當你想實際上線你的網頁時(也就是會有其他人會使用時),就需要考量 跨瀏覽器支援(cross browser testing) 。
第三方 APIs 不是來自瀏覽器原始創建,但你可以在網路上抓取他們的程式碼和信息。例如:
- The Twitter API allows you to do things like displaying your latest tweets on your website.
- The Google Maps API allows you to embed custom maps into your website, and other such functionality.
Note: These APIs are advanced, and we'll not be covering any of these in this module. You can find out much more about these in our Client-side web APIs module.
There's a lot more available, too! However, don't get over excited just yet. You won't be able to build the next Facebook, Google Maps or Instagram after studying JavaScript for 24 hours — there's a lot of basics to cover first. And that's why you're here — let's move on!
JavaScript 在你的頁面做了些什麼?
在這裡,我們將開始實際查看一些程式碼,並且在你的頁面上跑一些 JavaScript 程式碼的時候,探索探索實際發生了什麼。
讓我們簡要概括一下在瀏覽器上載入一個網頁時發生了怎樣的情況(首先在我們的 Css如何工作 這篇文章中有談論到)。當瀏覽器在載入一個網頁,就是在執行環境(瀏覽器選項卡)內部運行程式碼(HTML,CSS 和 Javascript)。這就像是 工廠採集一些原材料(程式中的code) 並且輸出成產品(看到的網頁)。
The JavaScript is executed by the browser's JavaScript engine, after the HTML and CSS have been assembled and put together into a web page. This ensures that the structure and style of the page are already in place by the time the JavaScript starts to run.
This is a good thing, as a very common use of JavaScript is to dynamically modify HTML and CSS to update a user interface, via the Document Object Model API (as mentioned above). If the JavaScript loaded and tried to run before the HTML and CSS was there to affect, then errors would occur.
瀏覽器安全性
Each browser tab is its own separate bucket for running code in (these buckets are called "execution environments" in technical terms) — this means that in most cases the code in each tab is run completely separately, and the code in one tab cannot directly affect the code in another tab — or on another website. This is a good security measure — if this were not the case, then pirates could start writing code to steal information from other websites, and other such bad things.
Note: There are ways to send code and data between different websites/tabs in a safe manner, but these are advanced techniques that we won't cover in this course.
JavaScript 運行指令
When the browser encounters a block of JavaScript, it generally runs it in order, from top to bottom. This means that you need to be careful what order you put things in. For example, let's return to the block of JavaScript we saw in our first example:
var para = document.querySelector('p'); para.addEventListener('click', updateName); function updateName() { var name = prompt('Enter a new name'); para.textContent = 'Player 1: ' + name; }
Here we are selecting a text paragraph (line 1), then attaching an event listener to it (line 3) so that when the paragraph is clicked, the updateName()
code block (lines 5–8) is run. The updateName()
code block (these types of reusable code block are called "functions") asks the user for a new name, and then inserts that name into the paragraph to update the display.
If you swapped the order of the first two lines of code, it would no longer work — instead, you'd get an error returned in the browser developer console — TypeError: para is undefined
. This means that the para
object does not exist yet, so we can't add an event listener to it.
Note: This is a very common error — you need to be careful that the objects referenced in your code exist before you try to do stuff to them.
解釋與編譯的程式碼
You might hear the terms interpreted and compiled in the context of programming. JavaScript is an interpreted language — the code is run from top to bottom and the result of running the code is immediately returned. You don't have to transform the code into a different form before the browser runs it.
Compiled languages on the other hand are transformed (compiled) into another form before they are run by the computer. For example C/C++ are compiled into assembly language that is then run by the computer.
Both approaches have different advantages, which we won't discuss at this point.
伺服器端與用戶端程式碼
You might also hear the terms server-side and client-side code, specially in the context of web development. Client-side code is code that is run on the user's computer — when a web page is viewed, the page's client-side code is downloaded, then run and displayed by the browser. In this JavaScript module we are explicitly talking about client-side JavaScript.
Server-side code on the other hand is run on the server, then its results are downloaded and displayed in the browser. Examples of popular server-side web languages include PHP, Python, Ruby, and ASP.NET. And JavaScript! JavaScript can also be used as a server-side language, for example in the popular Node.js environment — you can find more out about server-side JavaScript in our Dynamic Websites – Server-side programming topic.
The word dynamic is used to describe both client-side JavaScript, and server-side languages — it refers to the ability to update the display of a web page/app to show different things in different circumstances, generating new content as required. Server-side code dynamically generates new content on the server, e.g. pulling data from a database, whereas client-side JavaScript dynamically generates new content inside the browser on the client, e.g. creating a new HTML table, inserting data requested from the server into it, then displaying the table in a web page shown to the user. The meaning is slightly different in the two contexts, but related, and both approaches (server-side and client-side) usually work together.
A web page with no dynamically updating content is referred to as static — it just shows the same content all the time.
如何給頁面添加 JavaScript ?
JavaScript is applied to your HTML page in a similar manner to CSS. Whereas CSS uses <link>
elements to apply external stylesheets and <style>
elements to apply internal stylesheets to HTML, JavaScript only needs one friend in the world of HTML — the <script>
element. Let's learn how this works.
內部的 JavaScript
- First of all, make a local copy of our example file apply-javascript.html. Save it in a directory somewhere sensible.
- Open the file in your web browser and in your text editor. You'll see that the HTML creates a simple web page containing a clickable button.
- Next, go to your text editor and add the following just before your closing
</body>
tag:<script> // JavaScript goes here </script>
- Now we'll add some JavaScript inside our
<script>
element to make the page do something more interesting — add the following code just below the "// JavaScript goes here" line:function createParagraph() { var para = document.createElement('p'); para.textContent = 'You clicked the button!'; document.body.appendChild(para); } var buttons = document.querySelectorAll('button'); for (var i = 0; i < buttons.length ; i++) { buttons[i].addEventListener('click', createParagraph); }
- Save your file and refresh the browser — now you should see that when you click the button, a new paragraph is generated and placed below.
Note: If your example doesn't seem to work, go through the steps again and check that you did everything right. Did you save your local copy of the starting code as a .html
file? Did you add your <script>
element just before the </body>
tag? Did you enter the JavaScript exactly as shown? JavaScript is case sensitive, and very fussy, so you need to enter the syntax exactly as shown, otherwise it may not work.
Note: You can see this version on GitHub as apply-javascript-internal.html (see it live too).
外部的 JavaScript
這很不錯,但如果我們想放置我們的 JavaScript 在外部文件的文件應該怎麼做呢?讓我們來探索吧。
- 首先,創建一個新的文檔和你的 HTML 文檔同目錄,命名為
script.js
— 請確定這個文檔是用 .js 為文檔擴展名, 這樣它才能識別為 JavaScript。 - 下一步,複製所有腳本代碼從你現有的
<script>
元素並複製到 .js 文檔中,保存文檔。 - 現在,替換你現有的
<script>
元素並引用如下:<script src="script.js"></script>
- Save and refresh your browser, and you should see the same thing! It works just the same, but now we've got the JavaScript in an external file. This is generally a good thing in terms of organizing your code, and making it reusable across multiple HTML files. Plus the HTML is easier to read without huge chunks of script dumped in it.
Note: You can see this version on GitHub as apply-javascript-external.html and script.js (see it live too).
Inline JavaScript handlers
Note that sometimes you'll come across bits of actual JavaScript code living inside HTML. It might look something like this:
function createParagraph() { var para = document.createElement('p'); para.textContent = 'You clicked the button!'; document.body.appendChild(para); }
<button onclick="createParagraph()">Click me!</button>
You can try this version of our demo below.
This demo has exactly the same functionality as in the previous two sections, except that the <button>
element includes an inline onclick
handler to make the function run when the button is pressed.
Please don't do this, however. It is bad practice to pollute your HTML with JavaScript, and it is inefficient — you'd have to include the onclick="createParagraph()"
attribute on every button you wanted the JavaScript to apply to.
Using a pure JavaScript construct allows you to select all the buttons using one instruction. The code we used above to serve this purpose looks like this:
var buttons = document.querySelectorAll('button'); for (var i = 0; i < buttons.length ; i++) { buttons[i].addEventListener('click', createParagraph); }
This might look a bit longer than the onclick
attribute, but this will work for all buttons no matter how many are on the page, and how many are added or removed. The JavaScript does not need to be changed.
Note: Try editing your version of apply-javascript.html
and add a few more buttons into the file. When you reload, you should find that all of the buttons when clicked will create a paragraph. Neat, huh?
Comments
As with HTML and CSS, it is possible to write comments into your JavaScript code that will be ignored by the browser, and exist simply to provide instructions to your fellow developers on how the code works (and you, if you come back to your code after 6 months and can't remember what you did). Comments are very useful, and you should use them often, particularly for larger applications. There are two types:
- A single line comment is written after a double forward slash (//), e.g.
// I am a comment
- A multi-line comment is written between the strings /* and */, e.g.
/* I am also a comment */
So for example, we could annotate our last demo's JavaScript with comments like so:
// Function: creates a new paragraph and append it to the bottom of the HTML body. function createParagraph() { var para = document.createElement('p'); para.textContent = 'You clicked the button!'; document.body.appendChild(para); } /* 1. Get references to all the buttons on the page and sort them in an array. 2. Loop through all the buttons and add a click event listener to each one. When any button is pressed, the createParagraph() function will be run. */ var buttons = document.querySelectorAll('button'); for (var i = 0; i < buttons.length ; i++) { buttons[i].addEventListener('click', createParagraph); }
摘要
So there you go, your first step into the world of JavaScript. We've begun with just theory, to start getting you used to why you'd use JavaScript, and what kind of things you can do with it. Along the way you saw a few code examples and learned how JavaScript fits in with the rest of the code on your website, amongst other things.
JavaScript may seem a bit daunting right now, but don't worry — in this course we will take you through it in simple steps that will make sense going forward. In the next article we will plunge straight into the practical, getting you to jump straight in and build your own JavaScript examples.