Build your own function

2018-05-15 17:26 更新
先決條件: 基本的計(jì)算機(jī)素養(yǎng),對HTML和CSS的基本了解, JavaScript第一步函數(shù) - 可重復(fù)使用的代碼塊 。
目的: 提供一些實(shí)踐來構(gòu)建自定義函數(shù),并解釋一些更有用的相關(guān)細(xì)節(jié)。

主動學(xué)習(xí):讓我們構(gòu)建一個函數(shù)

我們將要構(gòu)建的自定義函數(shù)將被稱為 displayMessage(),它將在網(wǎng)站頂部向用戶顯示一個自定義消息框。 它將作為瀏覽器內(nèi)置的 alert() >功能。 您之前已經(jīng)看過,但我們只是刷新我們的記憶 - 在您的瀏覽器的JavaScript控制臺,在任何你喜歡的頁面嘗試以下:

alert('This is a message');

該函數(shù)接受單個參數(shù) - 警報(bào)框中顯示的字符串。 您可以嘗試更改字符串以更改消息。

警報(bào)功能不是真的那么好:你可以改變消息,但你不能輕易改變?nèi)魏纹渌珙伾?,或圖標(biāo)或任何其他。 我們將建立一個,將證明是更有趣。

注意:此示例應(yīng)在所有現(xiàn)代瀏覽器中正常工作,但在稍微老舊的瀏覽器中,樣式可能看起來有點(diǎn)滑稽。 我們建議您在Firefox,Opera或Chrome等現(xiàn)代瀏覽器中進(jìn)行此操作。

基本功能

首先,讓我們把一個基本功能放在一起。

注意:對于函數(shù)命名約定,您應(yīng)遵循與變量命名約定相同的規(guī)則。 這很好,你可以告訴他們分開 - 函數(shù)名稱后面帶圓括號,變量沒有。

  1. We'd like you to start this one off by accessing the function-start.html file and making a local copy. You'll see that the HTML is simple — our body contains just a single button. We've also provided some basic CSS to style the custom message box, and an empty <script> element to put our JavaScript in.
  2. Next, add the following inside the <script> element:
    function displayMessage() {
     
    }
    We start off with the keyword function, which means we are defining a function. This is followed by the name we want to give to our function, a set of parentheses, and a set of curly braces. Any parameters we want to give to our function go inside the parentheses, and the code that runs when we call the function goes inside the curly braces.
  3. Finally, add the following code inside the curly braces:
    var html = document.querySelector('html');
    
    var panel = document.createElement('div');
    panel.setAttribute('class', 'msgBox');
    html.appendChild(panel);
    
    var msg = document.createElement('p');
    msg.textContent = 'This is a message box';
    panel.appendChild(msg);
    
    var closeBtn = document.createElement('button');
    closeBtn.textContent = 'x';
    panel.appendChild(closeBtn);
    
    closeBtn.onclick = function() {
      panel.parentNode.removeChild(panel);
    }

這是相當(dāng)多的代碼,所以我們將逐步引導(dǎo)你。

第一行使用一個名為 document.querySelector()的DOM API函數(shù) > 以選擇 < html> / a>元素,并在一個名為 html 的變量中存儲對它的引用,因此我們可以稍后對其進(jìn)行處理:

var html = document.querySelector('html');

下一節(jié)使用另一個DOM API函數(shù) Document.createElement() > 創(chuàng)建 < div> / a>元素,并將其引用存儲在名為 panel 的變量中。 這個元素將是我們消息框的外部容器。

然后,我們使用又一個DOM API函數(shù) Element.setAttribute() > 在面板上設(shè)置 class 屬性,值為 msgBox 。 這是為了使元素更容易風(fēng)格 - 如果你看看頁面上的CSS,你會看到,我們使用一個 .msgBox 類選擇器來設(shè)置消息框及其內(nèi)容的樣式 。

最后,我們調(diào)用一個名為 Node.appendChild()的DOM函數(shù) 在我們之前存儲的 html 變量中,它將一個元素嵌套在另一個元素中作為它的子元素。 我們將< div> 面板指定為要附加在< html> 元素中的子元素。 我們需要這樣做,因?yàn)槲覀儎?chuàng)建的元素不會僅僅出現(xiàn)在頁面上 - 我們需要指定它放在哪里。

var panel = document.createElement('div');
panel.setAttribute('class', 'msgBox');
html.appendChild(panel);

接下來的兩個部分使用我們已經(jīng)看到的創(chuàng)建兩個新元素的相同的 createElement() appendChild()函數(shù) - //developer.mozilla.org/zh-CN/docs/Web/HTML/Element/p"> < p> .mozilla.org / zh-CN / docs / Web / HTML /元素/按鈕"> < button> - 并將其作為面板的子代插入頁面 < div> 。 我們使用其 Node.textContent 屬性 - 表示元素的文本內(nèi)容 - 在段落中插入消息,在按鈕內(nèi)部使用"x"。 當(dāng)用戶想要關(guān)閉消息框時,該按鈕將是需要被點(diǎn)擊/激活的按鈕。

var msg = document.createElement('p');
msg.textContent = 'This is a message box';
panel.appendChild(msg);

var closeBtn = document.createElement('button');
closeBtn.textContent = 'x';
panel.appendChild(closeBtn);

最后,我們使用 GlobalEventHandlers.onclick 事件 處理程序,以便當(dāng)單擊該按鈕時,運(yùn)行一些代碼以從頁面中刪除整個面板 - 關(guān)閉消息框。

簡單來說, onclick 處理程序是一個可用的按鈕(或?qū)嶋H上,頁面上的任何元素)的屬性,可以設(shè)置為一個函數(shù)來指定當(dāng)按鈕被點(diǎn)擊時運(yùn)行什么代碼。 您將在后面的活動文章中了解更多這些內(nèi)容。 我們使 onclick 處理程序等于一個匿名函數(shù),它包含當(dāng)單擊按鈕時運(yùn)行的代碼。 函數(shù)中的行使用 Node.removeChild() / a> DOM API函數(shù)指定要刪除HTML元素的特定子元素(在本例中為面板< div> )。

closeBtn.onclick = function() {
  html.removeChild(panel);
}

基本上,這整個代碼塊生成一個HTML塊,看起來像這樣,并將其插入頁面:

<div class="msgBox">
  <p>This is a message box</p>
  <button>x</button>
</div>

這是很多的代碼工作通過 - 不要擔(dān)心太多,如果你不記得確切的是,它的每一點(diǎn)的工作現(xiàn)在! 這里我們要關(guān)注的主要部分是函數(shù)的結(jié)構(gòu)和用法,但我們想要顯示一些有趣的例子。

調(diào)用函數(shù)

你現(xiàn)在已經(jīng)把你的函數(shù)定義寫入你的< script> 元素,但是它什么都不做。

  1. Try including the following line below your function to call it:
    displayMessage();
    This line invokes the function, making it run immediately. When you save your code and reload it in the browser, you'll see the little message box appear immediately, only once. We are only calling it once, after all.
  2. 現(xiàn)在,在示例頁面上打開瀏覽器開發(fā)者工具,轉(zhuǎn)到JavaScript控制臺并再次鍵入該行,您將看到它再次出現(xiàn)! 所以這很有趣 - 我們現(xiàn)在有一個可重用的函數(shù),我們可以隨時調(diào)用。

    但我們可能希望它出現(xiàn)以響應(yīng)用戶和系統(tǒng)操作。 在實(shí)際應(yīng)用中,這樣的消息框可能會響應(yīng)新數(shù)據(jù)可用或發(fā)生錯誤,或者用戶試圖刪除其配置文件("您確定這一點(diǎn)嗎?")或用戶添加 新聯(lián)系人和操作成功完成...等

    在這個演示中,我們將得到當(dāng)用戶單擊按鈕時顯示的消息框。

  3. Delete the previous line you added.
  4. Next, we'll select the button and store a reference to it in a variable. Add the following line to your code, above the function definition:
    var btn = document.querySelector('button');
  5. Finally, add the following line below the previous one:
    btn.onclick = displayMessage;
    In a similar way to our closeBtn.onclick... line inside the function, here we are calling some code in response to a button being clicked. But in this case, instead of calling an anonymous function containing some code, we are calling our function name directly.
  6. Try saving and refreshing the page — now you should see the message box appear when you click the button.

你可能會想知道為什么我們沒有在函數(shù)名之后包括括號。 這是因?yàn)槲覀儾幌肓⒓凑{(diào)用函數(shù) - 只有在單擊按鈕之后。 如果嘗試將行更改為

btn.onclick = displayMessage();

并保存并重新加載,您會看到消息框出現(xiàn),而沒有按鈕被點(diǎn)擊! 在這個上下文中的括號有時稱為"函數(shù)調(diào)用運(yùn)算符"。 只有當(dāng)要在當(dāng)前作用域中立即運(yùn)行函數(shù)時,才使用它們。 在同一方面,匿名函數(shù)中的代碼不會立即運(yùn)行,因?yàn)樗诤瘮?shù)范圍內(nèi)。

如果您嘗試了最后一次實(shí)驗(yàn),請確保在繼續(xù)之前撤消最后一次更改。

使用參數(shù)改進(jìn)函數(shù)

因?yàn)樗牵瘮?shù)仍然不是很有用 - 我們不想只是顯示相同的默認(rèn)消息每次。 讓我們通過添加一些參數(shù)來改進(jìn)我們的函數(shù),允許我們使用一些不同的選項(xiàng)來調(diào)用它。

  1. First of all, update the first line of the function:
    function displayMessage() {
    to this:
    function displayMessage(msgText, msgType) {
    Now when we call the function, we can provide two variable values inside the parentheses to specify the message to display in the message box, and the type of message it is.
  2. To make use of the first parameter, update the following line inside your function:
    msg.textContent = 'This is a message box';
    to
    msg.textContent = msgText;
  3. Last but not least, you now need to update your function call to include some updated message text. Change the following line:
    btn.onclick = displayMessage;
    to this block:
    btn.onclick = function() {
      displayMessage('Woo, this is a different message!');
    };
    If we want to specify parameters inside parentheses for the function we are calling, then we can't call it directly — we need to put it inside an anonymous function so that it isn't in the immediate scope and therefore isn't called immediately. Now it will not be called until the button is clicked.
  4. Reload and try the code again and you'll see that it still works just fine, except that now you can also vary the message inside the parameter to get different messages displayed in the box!

一個更復(fù)雜的參數(shù)

轉(zhuǎn)到下一個參數(shù)。 這將涉及更多的工作 - 我們將設(shè)置它,以便根據(jù) msgType 參數(shù)設(shè)置,該函數(shù)將顯示不同的圖標(biāo)和不同的背景顏色。

  1. First of all, download the icons needed for this exercise (warning and chat) from GitHub. Save them in a new folder called icons in the same location as your HTML file.
    Note: warning and chat icons found on iconfinder.com, and designed by Nazarrudin Ansyari. Thanks!
  2. Next, find the CSS inside your HTML file. We'll make a few changes to make way for the icons. First, update the .msgBox width from:
    width: 200px;
    to
    width: 242px;
  3. Next, add the following lines inside the .msgBox p { ... } rule:
    padding-left: 82px;
    background-position: 25px center;
    background-repeat: no-repeat;
  4. Now we need to add code to our displayMessage() function to handle displaying the icon. Add the following block just above the closing curly brace (}) of your function:
    if (msgType === 'warning') {
      msg.style.backgroundImage = 'url(icons/warning.png)';
      panel.style.backgroundColor = 'red';
    } else if (msgType === 'chat') {
      msg.style.backgroundImage = 'url(icons/chat.png)';
      panel.style.backgroundColor = 'aqua';
    } else {
      msg.style.paddingLeft = '20px';
    }
    Here, if the msgType parameter is set as 'warning', the warning icon is displayed and the panel's background color is set to red. If it is set to 'chat', the chat icon is displayed and the panel's background color is set to aqua blue. If the msgType parameter is not set at all (or to something different), then the else { ... } part of the code comes into play, and the paragraph is simply given default padding and no icon, with no background panel color set either. This provides a default state if no msgType parameter is provided, meaning that it is an optional parameter!
  5. Let's test out our updated function, try updating the displayMessage() call from this:
    displayMessage('Woo, this is a different message!');
    to one of these:
    displayMessage('Your inbox is almost full — delete some mails', 'warning');
    displayMessage('Brian: Hi there, how are you today?','chat');
    You can see how useful our (now not so) little function is becoming.

結(jié)論

恭喜您達(dá)成目標(biāo)! 本文介紹了構(gòu)建一個實(shí)用的自定義函數(shù)的整個過程,其中有一些工作可以移植到一個真正的項(xiàng)目中。 在下一篇文章中,我們將通過解釋另一個重要的相關(guān)概念 - 返回值來包裝函數(shù)。

    以上內(nèi)容是否對您有幫助:
    在線筆記
    App下載
    App下載

    掃描二維碼

    下載編程獅App

    公眾號
    微信公眾號

    編程獅公眾號