点击勘误issues (opens new window),哪吒感谢大家的阅读

让我们来组织一个基本的函数。

TIP

注:对于函数命名约定,应遵循与变量命名约定相同的规则。 这很好,尽你所能理解它们之间的区别 - 函数名称后带有括号,而变量则没有。

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

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

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

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

closeBtn.onclick = function() {
    panel.parentNode.removeChild(panel);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

第一行代码使用了一个DOM(文档对象模型)的内置方法 document.querySelector() 来选择<html> 元素并且把它存放在一个叫 html的常量中, 这样方便我们接下来使用这个元素:

const html = document.querySelector('html');
1

一个名字叫做 Document.createElement() 的DOM方法,用来创建 <div> 元素并且把该新建元素的引用(实际上是新建对象的地址)放在一个叫做 panel的常量中。 这个元素将成为我们的消息框的外部容器。

一个叫做 Element.setAttribute() 的DOM方法给panel元素添加了一个值为msgBox 的class 类属性。 这样做方便我们来给这个元素添加样式 — 查看CSS代码你就知道我们使用.msgBox 类选择器来给消息框和消息内容设置样式。

使用了一个叫做 Node.appendChild() 的DOM方法,给 html 常量(我们之前定义好的)追加了我们设置好样式的panel元素 。

# 使用参数列表改进函数

就现在看来,我们的函数还不是特别有用 — 我们想要的不仅仅是每点击一次展示一个默认的消息。我们来改造下我们的函数,给它添加几个参数, 允许我们以不同的方式调用这个函数。

第一步,修改函数的第一行代码:

function displayMessage() {
1

改成这样的:

function displayMessage(msgText, msgType) {
1

当我们调用函数的时候,我们可以在括号里添加两个变量,来指定显示在消息框里面的消息,和消息的类型。

为了使用第一个参数, 把接下来的一行:

msg.textContent = 'This is a message box';
1

改成这样:

msg.textContent = msgText;
1

最后但同样重要的一点, 我们来调用这个函数,并且使用了带参数的形式,修改下面这行:

btn.onclick = displayMessage;
1

改成这样:

btn.onclick = function() {
  displayMessage('Woo, this is a different message!');
};
1
2
3

如果我们要在点击事件里面绑定这个新函数,我们不能直接使用(btn.onclick = displayMessage('Woo, this is a different message!');)前面已经讲过— 我们要把它放在一个匿名函数里面,不然函数会直接调用,而不是按钮点击之后才会调用,这不是我们想要的结果。

保存刷新, 就像你所期待的那样现在你可以随意的指定消息框里面显示的消息!

上次更新: 1/19/2022, 3:07:00 AM