Build your own function

2018-05-15 17:26 更新
先决条件: 基本的计算机素养,对HTML和CSS的基本了解, JavaScript第一步函数 - 可重复使用的代码块
目的: 提供一些实践来构建自定义函数,并解释一些更有用的相关细节。

主动学习:让我们构建一个函数

我们将要构建的自定义函数将被称为 displayMessage(),它将在网站顶部向用户显示一个自定义消息框。 它将作为浏览器内置的 alert() >功能。 您之前已经看过,但我们只是刷新我们的记忆 - 在您的浏览器的JavaScript控制台,在任何你喜欢的页面尝试以下:

alert('This is a message');

该函数接受单个参数 - 警报框中显示的字符串。 您可以尝试更改字符串以更改消息。

警报功能不是真的那么好:你可以改变消息,但你不能轻易改变任何其他,如颜色,或图标或任何其他。 我们将建立一个,将证明是更有趣。

注意:此示例应在所有现代浏览器中正常工作,但在稍微老旧的浏览器中,样式可能看起来有点滑稽。 我们建议您在Firefox,Opera或Chrome等现代浏览器中进行此操作。

基本功能

首先,让我们把一个基本功能放在一起。

注意:对于函数命名约定,您应遵循与变量命名约定相同的规则。 这很好,你可以告诉他们分开 - 函数名称后面带圆括号,变量没有。

  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);
    }

这是相当多的代码,所以我们将逐步引导你。

第一行使用一个名为 document.querySelector()的DOM API函数 > 以选择 < html> / a>元素,并在一个名为 html 的变量中存储对它的引用,因此我们可以稍后对其进行处理:

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

下一节使用另一个DOM API函数 Document.createElement() > 创建 < div> / a>元素,并将其引用存储在名为 panel 的变量中。 这个元素将是我们消息框的外部容器。

然后,我们使用又一个DOM API函数 Element.setAttribute() > 在面板上设置 class 属性,值为 msgBox 这是为了使元素更容易风格 - 如果你看看页面上的CSS,你会看到,我们使用一个 .msgBox 类选择器来设置消息框及其内容的样式

最后,我们调用一个名为 Node.appendChild()的DOM函数 在我们之前存储的 html 变量中,它将一个元素嵌套在另一个元素中作为它的子元素。 我们将< div> 面板指定为要附加在< html> 元素中的子元素。 我们需要这样做,因为我们创建的元素不会仅仅出现在页面上 - 我们需要指定它放在哪里。

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

接下来的两个部分使用我们已经看到的创建两个新元素的相同的 createElement() appendChild()函数 - //developer.mozilla.org/zh-CN/docs/Web/HTML/Element/p"> < p> .mozilla.org / zh-CN / docs / Web / HTML /元素/按钮"> < button> - 并将其作为面板的子代插入页面 < div> 。 我们使用其 Node.textContent 属性 - 表示元素的文本内容 - 在段落中插入消息,在按钮内部使用"x"。 当用户想要关闭消息框时,该按钮将是需要被点击/激活的按钮。

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 事件 处理程序,以便当单击该按钮时,运行一些代码以从页面中删除整个面板 - 关闭消息框。

简单来说, onclick 处理程序是一个可用的按钮(或实际上,页面上的任何元素)的属性,可以设置为一个函数来指定当按钮被点击时运行什么代码。 您将在后面的活动文章中了解更多这些内容。 我们使 onclick 处理程序等于一个匿名函数,它包含当单击按钮时运行的代码。 函数中的行使用 Node.removeChild() / a> DOM API函数指定要删除HTML元素的特定子元素(在本例中为面板< div> )。

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

基本上,这整个代码块生成一个HTML块,看起来像这样,并将其插入页面:

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

这是很多的代码工作通过 - 不要担心太多,如果你不记得确切的是,它的每一点的工作现在! 这里我们要关注的主要部分是函数的结构和用法,但我们想要显示一些有趣的例子。

调用函数

你现在已经把你的函数定义写入你的< 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. 现在,在示例页面上打开浏览器开发者工具,转到JavaScript控制台并再次键入该行,您将看到它再次出现! 所以这很有趣 - 我们现在有一个可重用的函数,我们可以随时调用。

    但我们可能希望它出现以响应用户和系统操作。 在实际应用中,这样的消息框可能会响应新数据可用或发生错误,或者用户试图删除其配置文件("您确定这一点吗?")或用户添加 新联系人和操作成功完成...等

    在这个演示中,我们将得到当用户单击按钮时显示的消息框。

  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.

你可能会想知道为什么我们没有在函数名之后包括括号。 这是因为我们不想立即调用函数 - 只有在单击按钮之后。 如果尝试将行更改为

btn.onclick = displayMessage();

并保存并重新加载,您会看到消息框出现,而没有按钮被点击! 在这个上下文中的括号有时称为"函数调用运算符"。 只有当要在当前作用域中立即运行函数时,才使用它们。 在同一方面,匿名函数中的代码不会立即运行,因为它在函数范围内。

如果您尝试了最后一次实验,请确保在继续之前撤消最后一次更改。

使用参数改进函数

因为它是,函数仍然不是很有用 - 我们不想只是显示相同的默认消息每次。 让我们通过添加一些参数来改进我们的函数,允许我们使用一些不同的选项来调用它。

  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!

一个更复杂的参数

转到下一个参数。 这将涉及更多的工作 - 我们将设置它,以便根据 msgType 参数设置,该函数将显示不同的图标和不同的背景颜色。

  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.

结论

恭喜您达成目标! 本文介绍了构建一个实用的自定义函数的整个过程,其中有一些工作可以移植到一个真正的项目中。 在下一篇文章中,我们将通过解释另一个重要的相关概念 - 返回值来包装函数。

    以上内容是否对您有帮助:
    在线笔记
    App下载
    App下载

    扫描二维码

    下载编程狮App

    公众号
    微信公众号

    编程狮公众号