fix(guide): simplify directory structure

This commit is contained in:
Mrugesh Mohapatra
2018-10-16 21:26:13 +05:30
parent f989c28c52
commit da0df12ab7
35752 changed files with 0 additions and 317652 deletions

View File

@ -0,0 +1,26 @@
---
title: Add New Properties to a JavaScript Object
localeTitle: 将新属性添加到JavaScript对象
---
您可以像修改现有JavaScript对象一样向现有JavaScript对象添加新属性。
有两种不同的语法,点表示法和括号表示法。为了便于阅读,通常首选点符号,但属性必须是有效的标识符。
以下是使用点符号的方法:
```
myDog.bark = "woof-woof";
```
以下是使用括号表示法的方法:
```javascript
myObject['bark'] = "woof-woof";
```
使用括号表示法,我们可以将变量用作属性名称:
```javascript
var dynamicProperty = "bark";
myObject[dynamicProperty] = "woof-woof";
```

View File

@ -0,0 +1,9 @@
---
title: Add Two Numbers with JavaScript
localeTitle: 使用JavaScript添加两个数字
---
JavaScript使用`+`符号进行添加。它也可以用来代替`parseInt()`但这超出了这个范围。
```
var sum = 10 + 10;
```

View File

@ -0,0 +1,28 @@
---
title: Build JavaScript Objects
localeTitle: 构建JavaScript对象
---
对象对于以结构化方式存储数据很有用,并且可用于表示现实世界对象,例如汽车或酒店到计算机。
对象类似于数组除了不使用索引访问和修改数据您可以通过所谓的属性访问对象中的数据。主要有两种创建对象的方法Object Literal和Constructor方式。
使用Object Literal方式我们将如何创建示例对象
```
var cat = {
name: "Whiskers",
legs: 4,
tails: 1,
enemies: ["Water", "Dogs"]
};
```
使用构造函数方式,我们将如何创建示例对象:
```
var cat = new Object();
cat.name = "Whiskers";
cat.legs = 4;
cat.tails = 1;
cat.enemies = ["Water", "Dogs"];
```
在构造函数方式中,我们将`new`关键字与`Object` 使用大写“O”一起使用来创建新的对象实例。之后我们使用点表示法来分配对象的属性名称和值。

View File

@ -0,0 +1,22 @@
---
title: Comment Your JavaScript Code
localeTitle: 评论您的JavaScript代码
---
评论是留给自己和其他人的好方法,后者需要弄清楚它的作用。其中的任何代码都将被忽略。
我们来看看用JavaScript编写注释的两种方法。
* 双斜杠注释将注释掉当前行的文本的其余部分:
`// This is a single line comment.`
* 斜杠 - 星 - 星 - 斜杠评论将注释掉`/*``*/`字符之间的所有内容:
```javascript
/*
This is
a multi-line comment
(comment block)
*/
```

View File

@ -0,0 +1,17 @@
---
title: Construct JavaScript Objects with Functions
localeTitle: 用函数构造JavaScript对象
---
使用构造函数,可以使用蓝图或构造函数轻松创建新对象。声明语法略有不同,但仍然易于记忆。
```
// Let's add the properties engines and seats to the car in the same way that the property wheels has been added below. They should both be numbers.
var Car = function() {
this.wheels = 4;
this.engines = 1;
this.seats = 1;
};
var myCar = new Car();
```
构造函数的名称通常以大写字母开头与其他函数不同后者往往以小写字符开头。大写字母应该有助于提醒开发人员在使用该函数创建对象时使用new关键字。

View File

@ -0,0 +1,11 @@
---
title: Create a JavaScript Slot Machine
localeTitle: 创建一个JavaScript老虎机
---
为此,我们必须使用他们给出的公式而不是一般公式生成三个随机数。 `Math.floor(Math.random() * (3 - 1 + 1)) + 1;`
```
slotOne = Math.floor(Math.random() * (3 - 1 + 1)) + 1;
slotTwo = Math.floor(Math.random() * (3 - 1 + 1)) + 1;
slotThree = Math.floor(Math.random() * (3 - 1 + 1)) + 1;
```

View File

@ -0,0 +1,9 @@
---
title: Create Decimal Numbers with JavaScript
localeTitle: 使用JavaScript创建十进制数
---
JavaScript数字变量可以包含小数。
```
var myDecimal = 2.8;
```

View File

@ -0,0 +1,90 @@
---
title: Debugging JavaScript with Browser Devtools
localeTitle: 使用浏览器Devtools调试JavaScript
---
作为开发人员,您经常需要调试代码。您可能已经在一些挑战中使用了`console.log` ,这是最简单的调试方法。
在本文中,我们将告诉您一些最酷的技巧,使用浏览器的本机调试工具进行调试。
## 简要了解FreeCodeCamp代码编辑器
在进入调试之前让我们泄漏一些有关FCC _真棒代码检查引擎的_秘密事实。
我们使用自定义的[CodeMirror](http://codemirror.net/mode/javascript/index.html)作为代码编辑器。 [`eval()`函数](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval)用于评估编辑器中表示为字符串的JavaScript代码。调用`eval()` ,浏览器将本机执行您的代码。我们将在本文后面的部分中了解更多为什么这个秘密很重要。
## 现在转向技巧:
## 谷歌Chrome DevTools
谷歌浏览器是最流行的浏览器之一内置JavaScript引擎[V8](https://developers.google.com/v8/) ,为开发人员提供了一个很棒的工具集,名为[Chrome DevTools](https://developer.chrome.com/devtools) 。强烈建议您访问他们的[完整JavaScript调试指南](https://developer.chrome.com/devtools/docs/javascript-debugging) 。
### 1DevTools的基础知识
#### 启动Chrome DevTools
点击`F12`
。或者你可以按
`Ctrl` + `Shift` + `I`
在Windows和Linux或
`Cmd` + `Shift` + `I`
在Mac上或者如果您只是喜欢鼠标请转到`Menu > More Tools > Developer Tools`
#### 了解`Sources`和`console`选项卡。
在调试时,这两个选项卡可能是您最好的朋友。 “ `Sources`选项卡可用于显示您正在访问的网页上的所有脚本。此选项卡包含代码窗口,文件树,调用堆栈和监视窗口等部分。
`console`选项卡是所有日志输出的位置。此外您可以使用控制台选项卡的提示来执行JavaScript代码。它类似于Windows上的命令提示符或Linux上的终端。
_提示使用`Esc`键随时在DevTools中切换控制台。_
### 2常用快捷方式和功能
虽然您可以访问[完整的快捷方式列表](https://developers.google.com/web/tools/chrome-devtools/iterate/inspect-styles/shortcuts) ,但以下是一些最常用[的快捷方式](https://developers.google.com/web/tools/chrome-devtools/iterate/inspect-styles/shortcuts)
功能WindowsLinux Mac
搜索关键字,支持正则表达式。 `Ctrl` + `F``Cmd` + `F`
搜索并打开文件`Ctrl` + `P``Cmd` + `P`
跳转到`Ctrl` + `G` +行`:line_no``Cmd` + `G` + `:line_no`
添加断点`Ctrl` + `B` ,或单击行号。 `Cmd` + `B` 或点击第no行。
暂停/恢复脚本执行`F8` `F8`
跳过下一个函数调用`F10` `F10`
进入下一个函数调用`F11` `F11`
### 3为我们的代码使用源映射
您最喜欢的功能之一是通过[源映射](https://developer.chrome.com/devtools/docs/javascript-debugging#source-maps) [动态调试动态脚本](https://developer.chrome.com/devtools/docs/javascript-debugging#breakpoints-dynamic-javascript) 。
每个脚本都可以在DevTools的Source选项卡中可视化。源选项卡包含所有JavaScript源文件。但代码编辑器中的代码通过`eval()`在浏览器进程中简称为虚拟机VM的容器中执行。
您可能已经猜到我们的代码实际上是一个没有文件名的脚本。所以我们在Source选项卡中没有看到。
> ![:sparkles:](//forum.freecodecamp.com/images/emoji/emoji_one/sparkles.png?v=2 ":闪耀:") **_黑客来了_** ![:sparkles:](//forum.freecodecamp.com/images/emoji/emoji_one/sparkles.png?v=2 ":闪耀:")
我们必须利用`Source Maps`从编辑器中为JavaScript指定一个名称。它非常简单
让我们说我们正在使用[Factorialize](https://www.freecodecamp.com/challenges/factorialize-a-number)挑战,我们的代码如下所示:
```
function factorialize(num) {
if(num <= 1){
...
}
factorialize(5);
```
我们需要做的就是将`//# sourceURL=factorialize.js`添加到代码的顶部,即第一行:
```
//# sourceURL=factorialize.js
function factorialize(num) {
if(num <= 1){
...
```
> ![:sparkles:](//forum.freecodecamp.com/images/emoji/emoji_one/sparkles.png?v=2 ":闪耀:") **_而尤里卡就是这样_** ![:sparkles:](//forum.freecodecamp.com/images/emoji/emoji_one/sparkles.png?v=2 ":闪耀:")
现在打开DevTools并搜索文件名。添加断点调试远离并享受

View File

@ -0,0 +1,48 @@
---
title: Debugging Node files using CLI commands
localeTitle: 使用CLI命令调试节点文件
---
## 使用CLI命令调试节点文件
在本教程中您将学习如何在命令行上调试Node.js代码。您可以使用浏览器的DevTools轻松调试纯JavaScript代码。对于Node您可以在不离开命令行界面CLI的情况下调试代码。
假设您有一个名为`contents.js`的文件。您将使用`node`命令运行该文件。
```bash
node contents.js
```
由于您正在编写Node.js代码因此必须已经知道这一点。现在必须调试弹出的任何错误。要在调试模式下运行该文件请在运行该文件时附加关键字`inspect`
```bash
node inspect contents.js
```
现在,此命令将以调试模式打开您的文件。从这里开始,您可以通过按键盘上的**N**键一次一行地执行代码。
调试器将从第一行开始。按**N** 可以将调试器移动到下一行。如果第一行出错则会显示错误而不是移动到第二行。这非常有用。例如如果第17行出现错误它将在向前移动之前显示错误。
您的逻辑中可能存在错误,这意味着您希望显示某个值,而是显示不同的值。在这种情况下,添加`console.log()`可能会对您有所帮助,并且在调试模式下,更容易识别错误原因。
* * *
现在有时候你的源代码很大。您进入调试模式以调试错误并确定错误来自第52行的函数。但是由于调试模式从第1行开始您是否别无选择只能逐行访问第52行绝对不
只需在函数前添加关键字`debugger`
```javascript
console.log("Outside the function....everything's going smoothly");
debugger;
function doesSomething() {
//some logic
console.log("Something went wrong inside here!");
}
```
现在再次以调试模式打开文件,这次按键盘上的**C.**
按**N**将调试器移动到下一行,按**C键**告诉调试器一次完成整个代码。这与没有调试模式的情况相同。 _但是_ ,这次你的代码还有一个补充。你猜对了 - `debugger`关键字。按**C**通常会运行代码直到结束,但由于添加`debugger` ,它将在函数启动之前停止。
因此,在调试模式下运行文件后,按**C**将跳过代码并在`debugger`关键字的函数之前停止。之后,您可以一次开始逐行执行该功能,直到找到错误为止。

View File

@ -0,0 +1,34 @@
---
title: Declare JavaScript Objects as Variables
localeTitle: 将JavaScript对象声明为变量
---
这有一个简单的格式。您声明您的变量并使其等于`{ key: value}`形式的对象
```
var car = {
"wheels":4,
"engines":1,
"seats":5
};
```
您可以使用点表示法或括号表示法访问对象的属性。
使用点符号:
```javascript
console.log(car.wheels); // 4
```
使用括号表示法:
```javascript
console.log(car["wheels"]); // 1
```
使用动态括号表示法:
```javascript
var seatsProperty = "seats";
console.log(car[seatsProperty]); // 5
```

View File

@ -0,0 +1,98 @@
---
title: Declare Variables
localeTitle: 声明变量
---
# 声明变量
JavaScript变量声明可以分为三个不同的组件变量类型变量名称和变量值。
```js
var myName = "Rafael";
```
让我们将上面的代码行分解为构成它的部分:
```js
var/const/let
```
JavaScript变量可以有三种声明类型varconst和let。 Var类型变量是全局的如果在函数外部声明它们可以被任何JS文件或控制台访问并且如果在函数内创建它们则无论块范围如何都可以访问它们。令型变量的范围受限于它们的块。请参阅下面的示例了解差异。
```js
function varTest() {
var x = 1;
if (true) {
var x = 2; // same variable!
console.log(x); // 2
}
console.log(x); // 2
}
function letTest() {
let x = 1;
if (true) {
let x = 2; // different variable
console.log(x); // 2
}
console.log(x); // 1
}
```
Const类型变量与let变量块作用域具有相同的作用域但是是不可变的。无论要赋值const-type变量的值是什么都必须在声明变量时发生如果稍后更改变量JavaScript将抛出错误。
```js
const genre = "non-fiction";
console.log(genre); // "non-fiction";
genre = "fantasy"; // error
```
现在我们可以确定变量类型是什么,让我们来看看名称。 JavaScript变量名以`camel case`格式编写。驼峰案例的一个例子是: `camelCase` 。在我们的例子中:
```js
myName
```
该名称也是我们稍后将再次访问该变量:
```js
console.log(myName); // "Rafael"
```
最后,我们的价值:
```js
"Rafael"
```
JavaScript是动态类型的这意味着任何给定的变量都可以在任何给定时间表示任何给定的数据类型。例如
```js
var example = "This is an example";
example = [0, 1, 2, 3]
example = {test: "Result"}
example = 5
```
所有这些语句都是完全有效的 - JavaScript变量可以从字符串跳转到数组从对象跳转到整数。
### 将对象声明为const
如上所述const变量是不可变的意味着在声明时分配给这样的变量的值不能更新但是在使用const的对象声明的情况下有一点需要注意。类型const的对象也不能在定义后更新但对象cab的属性是。例如。
```js
const Car1 = {
name: 'BMW',
model: 'X1',
color: 'black'
}
```
在这里,我们无法更新对象,但我们可以通过点(。)运算符访问来更新属性,如下所示。
```js
Car1.color = 'Red';
console.log(Car1);
O/P - {name: "BMW", model: "X1", color: "Red"}
```
如果我们需要将enitre对象设为不可变包括属性那么我们必须使用freeze方法。

View File

@ -0,0 +1,15 @@
---
title: Decrement a Number with JavaScript
localeTitle: 使用JavaScript减少数字
---
您可以使用`--`运算符轻松地将变量减1或减`1`
```
i--;
```
相当于
```
i = i - 1;
```
**注意:**整条线变为`i--;` ,消除了对等号的需要。

View File

@ -0,0 +1,41 @@
---
title: Delete Properties from a JavaScript Object
localeTitle: 从JavaScript对象中删除属性
---
我们还可以删除对象中的属性,如下所示:
```
delete ourDog.bark;
```
**delete运算符**从对象中删除属性。
## 句法
`delete expression`应该求值为属性引用的表达式,例如:
```
delete object.property
delete object['property']
```
## 参数
**目的**
对象的名称或评估对象的表达式。
**属性**
要删除的属性。
## 例
```js
var person = {name:'Jay', age:'52'};
delete person['age'];
console.log(person); //{name:'Jay'}
```
## 返回值
如果属性是自己的不可配置属性则以严格模式抛出在非严格中返回false。在所有其他情况下返回true。
[阅读更多](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete)

View File

@ -0,0 +1,27 @@
---
title: Detect authentic click events
localeTitle: 检测可靠的点击事件
---
## 检测可靠的点击事件
可能存在这样的情况只有当用户真正触发click事件而不是某个脚本来模拟click事件时才想要执行某些特定事情。
这个问题有一个非常简单的解决方案javascript事件对象为我们提供了一个`.istrusted`属性,可以用它来区分。
#### 以下是使用此方法的示例
```javascript
// Assume there is a button in the HTML
const button = document.querySelector('button');
button.addEventListener('click', (e) => {
if (e.isTrusted) {
console.log('Button clicked by a real user');
} else {
console.log('Button click simulated by a script');
}
});
button.click() // Outputs "Button click simulated by a script"
```

View File

@ -0,0 +1,9 @@
---
title: Divide One Number by Another with JavaScript
localeTitle: 用JavaScript划分一个号码
---
JavaScript使用`/`符号进行划分。
```
var quotient = 66 / 33;
```

View File

@ -0,0 +1,23 @@
---
title: Finding a Remainder in JavaScript
localeTitle: 在JavaScript中查找剩余内容
---
_余数运算符_ `%`给出了两个数的除法的余数。
## 例
```
5 % 2 = 1 because
Math.floor(5 / 2) = 2 (Quotient)
2 * 2 = 4
5 - 4 = 1 (Remainder)
```
## 用法
在数学中通过检查数字除法的余数为2可以检查偶数或奇数。
```
17 % 2 = 1 (17 is Odd)
48 % 2 = 0 (48 is Even)
```
**注意**不要将它与_模数_ `%`混淆,否则与负数不兼容。

View File

@ -0,0 +1,5 @@
---
title: Generate Random Fractions with JavaScript
localeTitle: 使用JavaScript生成随机分数
---
JavaScript有一个`Math.random()`函数,可生成一个随机十进制数。

View File

@ -0,0 +1,11 @@
---
title: Generate Random Whole Numbers with JavaScript
localeTitle: 使用JavaScript生成随机整数
---
很高兴我们可以创建随机十进制数,但如果我们生成一个随机整数更有用,它会更有用。
为实现此目的我们可以将随机数乘以10并使用`Math.floor()`将十进制数转换为整数
```
Math.floor(Math.random()*10)
```

View File

@ -0,0 +1,15 @@
---
title: Get Current Url in JavaScript
localeTitle: 在JavaScript中获取当前URL
---
要获取**当前网址**
```
var url = window.location.href;
```
要获取**当前路径**
```
var path = window.location.path;
```
有关位置对象及其属性的更多信息,请参见[此处](https://developer.mozilla.org/en-US/docs/Web/API/Window/location) 。

View File

@ -0,0 +1,11 @@
---
title: Give Your JavaScript Slot Machine Some Stylish Images
localeTitle: 给你的JavaScript老虎机一些时尚的图像
---
我们已经在一个名为images的数组中为你设置了图像。我们可以使用不同的索引来获取每个索引。
以下是我们如何设置第一个插槽以显示不同的图像,具体取决于其随机数生成的数字:
```
$($('.slot')[0]).html('<img src = "' + images[slotOne-1] + '">');
```

View File

@ -0,0 +1,62 @@
---
title: How to Create a Countdown Timer
localeTitle: 如何创建倒数计时器
---
## 如何创建倒数计时器
### 创建
首先构建countdownTimer函数。
```javascript
function startCountdown(seconds){
var counter = seconds;
var interval = setInterval(() => {
console.log(counter);
counter--;
if(counter < 0 ){
// The code here will run when
// the timer has reached zero.
clearInterval(interval);
console.log('Ding!');
};
}, 1000);
};
```
### 执行
现在,为了启动计时器,我们提供了`startCountdown()`其中一个数值作为参数,表示倒计时的秒数。
```javascript
startCountdown(10);
// Console Output //
// 10
// 9
// 8
// 7
// 6
// 5
// 4
// 3
// 2
// 1
// 0
// Ding!
```
### 实例
[Codepen - 倒数计时器](https://codepen.io/rdev-rocks/pen/jLogxY?editors=0012)
### 更多资源
使用的方法:
* [的setInterval](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval)
* [clearInterval](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval)

View File

@ -0,0 +1,245 @@
---
title: How to Create a Dropdown Menu with CSS and JavaScript
localeTitle: 如何使用CSS和JavaScript创建下拉菜单
---
## 如何使用CSS和JavaScript创建下拉菜单
在本教程中您将学习如何使用vanilla JavascriptHTML和CSS创建一个简单的下拉菜单。我们将介绍HTMLCSS和Javascript代码但更多地关注编程因为这是一个JS教程。我们将只使用普通的JS和CSS没有框架或预处理器。唯一种类异常将导入[Font Awesome](https://fontawesome.com/) CSS文件因为我们将使用其中一个图标。
这是针对平均了解HTMLCSS和JS的开发人员。我试图让它尽可能干净但我不会过分关注细节。我希望你们都喜欢。
## 截图
这是代码结果的样子:
初始屏幕:
![](https://i.imgur.com/jrnu6mE.png)
下拉开启:
![](https://i.imgur.com/gszPtRa.png)
下拉选项已选中:
![](https://i.imgur.com/TKXxZGF.png)
#### HTML
在本节中我们将讨论演示页面的HTML代码的实现。 首先,让我们看一下`<head>`代码
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Dropdown Example</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/'-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="styles.css">
</head>
```
这基本上是HTML头文件样板除了加载我们将在本教程中使用的两个CSS样式表的`link`标记Font Awesome样式和`styles.css`文件,我们将在其中定义此页面的样式。
然后还有HTML文件的其余部分正文
```html
<body>
<div class='dropdown'>
<div class='title pointerCursor'>Select an option <i class="fa fa-angle-right"></i></div>
<div class='menu pointerCursor hide'>
<div class='option' id='option1'>Option 1</div>
<div class='option' id='option2'>Option 2</div>
<div class='option' id='option3'>Option 3</div>
<div class='option' id='option4'>Option 4</div>
</div>
</div>
<span id='result'>The result is: </span>
<script>
...
</script>
</body>
</html>
```
本节可分为3个主要部分
* `.dropdown` div将定义下拉元素的结构。
* `#result`元素,将包含用户选择的选项,来自下拉列表元素。
* 写入`<script>`标记的`<script>` 。它的实现在这里隐藏,因为它的细节将在本教程的最后一节中解释。
dropdown元素是一个包含`title``menu`元素的`div` 。前者只定义在选择任何选项之前将在元素上显示的文本,后者将定义元素可选择的选项。
`result`元素只是为了显示当前选择的选项。
#### 样式:
您可以在下面查看完整的css代码。正如您所看到的它使用了CSS3 `transition``transform`结构。
请注意`.dropdown`类的定义。这些用于定义下拉容器组件及其内部元素的布局,例如`.title`及其`.option`
```css
body{
font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
}
.hide {
max-height: 0 !important;
}
.dropdown{
border: 0.1em solid black;
width: 10em;
margin-bottom: 1em;
}
.dropdown .title{
margin: .3em .3em .3em .3em;
width: 100%;
}
.dropdown .title .fa-angle-right{
float: right;
margin-right: .7em;
transition: transform .3s;
}
.dropdown .menu{
transition: max-height .5s ease-out;
max-height: 20em;
overflow: hidden;
}
.dropdown .menu .option{
margin: .3em .3em .3em .3em;
margin-top: 0.3em;
}
.dropdown .menu .option:hover{
background: rgba(0,0,0,0.2);
}
.pointerCursor:hover{
cursor: pointer;
}
.rotate-90{
transform: rotate(90deg);
}
```
#### JavaScript的
现在我们将看到Javascript部分是如何实现的。我们将首先介绍函数定义 然后调用这些函数的代码使下拉动作发生。
基本上根据用户交互的内容有3个动作因为他们的侦听器被添加到DOM元素
1. 单击下拉元素
2. 选择其中一个下拉选项
3. 更改当前选定的选项
我想说明我们使用的是箭头函数( `() => {}` )和`const`关键字它们是ES6的特性。如果你使用的是最新版本的浏览器那么你可能会很好但请记住这一点。
#### 1.单击下拉元素
```Javascript
function toggleClass(elem,className){
if (elem.className.indexOf(className) !== -1){
elem.className = elem.className.replace(className,'');
}
else{
elem.className = elem.className.replace(/\s+/g,' ') + ' ' + className;
}
return elem;
}
function toggleDisplay(elem){
const curDisplayStyle = elem.style.display;
if (curDisplayStyle === 'none' || curDisplayStyle === ''){
elem.style.display = 'block';
}
else{
elem.style.display = 'none';
}
}
function toggleMenuDisplay(e){
const dropdown = e.currentTarget.parentNode;
const menu = dropdown.querySelector('.menu');
const icon = dropdown.querySelector('.fa-angle-right');
toggleClass(menu,'hide');
toggleClass(icon,'rotate-90');
}
```
单击下拉元素时,它将打开(如果已关闭)或关闭(如果已打开)。这通过将`toggleMenuDisplay`绑定到下拉列表元素上的click事件侦听器来实现。此函数通过使用`toggleDisplay``toggleClass`函数切换其`menu`元素的显示。
#### 2.选择其中一个下拉选项
```Javascript
function handleOptionSelected(e){
toggleClass(e.target.parentNode, 'hide');
const id = e.target.id;
const newValue = e.target.textContent + ' ';
const titleElem = document.querySelector('.dropdown .title');
const icon = document.querySelector('.dropdown .title .fa');
titleElem.textContent = newValue;
titleElem.appendChild(icon);
//trigger custom event
document.querySelector('.dropdown .title').dispatchEvent(new Event('change'));
//setTimeout is used so transition is properly shown
setTimeout(() => toggleClass(icon,'rotate-90',0));
}
```
#### 3.更改当前选择的选项
```Javascript
function handleTitleChange(e){
const result = document.getElementById('result');
result.innerHTML = 'The result is: ' + e.target.textContent;
}
```
函数`handleTitleChange`绑定到`.title`元素上的自定义`change`事件以便在title元素更改时更改`#result`元素内容。此事件的触发在上一节中完成。
#### 主要代码
```Javascript
//get elements
const dropdownTitle = document.querySelector('.dropdown .title');
const dropdownOptions = document.querySelectorAll('.dropdown .option');
//bind listeners to these elements
dropdownTitle.addEventListener('click', toggleMenuDisplay);
dropdownOptions.forEach(option => option.addEventListener('click',handleOptionSelected));
document.querySelector('.dropdown .title').addEventListener('change',handleTitleChange);
```
在主要部分中,只有一些简单的代码可以获取下拉列表的标题和选项元素,以便将最后一节中讨论的事件绑定到它们。
## 演示
可在[此处](https://codepen.io/GCrispino/pen/EEXmYd)找到此应用程序的完整代码和演示。
## 更多信息
* [ES6介绍](https://guide.freecodecamp.org/javascript/es6)
* [箭头功能](https://guide.freecodecamp.org/javascript/es6/arrow_functions/)
* [让和Const](https://guide.freecodecamp.org/javascript/es6/let_and_const/)

View File

@ -0,0 +1,569 @@
---
title: How to Create a Lightbox
localeTitle: 如何创建灯箱
---
## 如何创建灯箱
### 介绍
灯箱是两个组件的组合, [模态](https://en.wikipedia.org/wiki/Modal_window)和幻灯片放映。在这里,您将使用`HTML` `CSS``JavaScript`构建一个简单的灯箱。
灯箱将包含在模式中,该模式将由一些`JavaScript``HTML`标记中的[事件处理程序](https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Event_handlers)触发。 您将构建将使用`JavaScript`为状态提供`CSS`和行为的`CSS` 。您还可以在底部找到您使用的方法的参考列表以及与本教程相关的其他有用的tid位。
#### 我们的形象
我们将使用的图像由[Pexels](https://www.pexels.com/)提供, 一个免费的库存照片库,允许您快速,免费地为他们的项目提供高质量的图像,通常没有所需的属性。
#### 只是告诉我代码!
这里有一个实例可以找到[\- CodePen / Lightbox](https://codepen.io/rdev-rocks/pen/KXNzvo)和代码的完整草案接近底部。
### 第1步。标记
标记或`HTML`提供灯箱的结构。
```html
<!-- Here is your access point for your user, a preview of the images you wish to display.
You use the onclick="" event handler to execute the methods you will define in the
JavaScript near the bottom -->
<div class="row">
<div class="col">
<img src="https://static.pexels.com/photos/385997/pexels-photo-385997.jpeg" onclick="openLightbox();toSlide(1)" class="hover-shadow preview" alt="Toy car on the road." />
</div>
<div class="col">
<img src="https://static.pexels.com/photos/574521/pexels-photo-574521.jpeg" onclick="openLightbox();toSlide(2)" class="hover-shadow preview" alt="Toy car exploring offroad." />
</div>
<div class="col">
<img src="https://static.pexels.com/photos/386009/pexels-photo-386009.jpeg" onclick="openLightbox();toSlide(3)" class="hover-shadow preview" alt="Toy car in the city." />
</div>
</div>
<!-- This is your lightbox, it is contained in a modal. Here you provide all the images,
controls, and another set of preview images as the dots. Dots show your user which
image is currently active. Note that you use entities (eg &times;), more info on
them at the bottom. -->
<div id="Lightbox" class="modal">
<span class="close pointer" onclick="closeLightbox()">&times;</span>
<div class="modal-content">
<div class="slide">
<img src="https://static.pexels.com/photos/385997/pexels-photo-385997.jpeg" class="image-slide" alt="Toy car on the road." />
</div>
<div class="slide">
<img src="https://static.pexels.com/photos/574521/pexels-photo-574521.jpeg" class="image-slide" alt="Toy car exploring offroad." />
</div>
<div class="slide">
<img src="https://static.pexels.com/photos/386009/pexels-photo-386009.jpeg" class="image-slide" alt="Toy car in the city." />
</div>
<a class="previous" onclick="changeSlide(-1)">&#10094;</a>
<a class="next" onclick="changeSlide(1)">&#10095;</a>
<div class="dots">
<div class="col">
<img src="https://static.pexels.com/photos/385997/pexels-photo-385997.jpeg" class="modal-preview hover-shadow" onclick="toSlide(1)" alt="Toy car on the road" />
</div>
<div class="col">
<img src="https://static.pexels.com/photos/574521/pexels-photo-574521.jpeg" class="modal-preview hover-shadow" onclick="toSlide(2)" alt="Toy car exploring offroad." />
</div>
<div class="col">
<img src="https://static.pexels.com/photos/386009/pexels-photo-386009.jpeg" class="modal-preview hover-shadow" onclick="toSlide(3)" alt="Toy car in the city." />
</div>
</div>
</div>
</div>
```
### 第2步。使用CSS样式
`CSS`为您的灯箱提供不同的状态。可见性,定位和悬停效果等。
您的样式表应如下所示:
```css
/* Here you provide a best practice's "reset", read more about it at the bottom! :) */
html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
body {
margin: 0;
}
/* You define the style of our previews here, you are using flex to display the images
"responsively". */
.preview {
width: 100%;
}
.row {
display: flex;
flex-direction: row;
justify-content: space-between;
}
.row > .col {
padding: 0 8px;
}
.col {
float: left;
width: 25%;
}
/* Now you want to define what the lightbox will look like. Note that you have the display
as none. You don't want it to show until the user clicks on one of the previews.
You will change this display property with JavaScript below. */
.modal {
display: none;
position: fixed;
z-index: 1;
padding: 10px 62px 0px 62px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: black;
}
.modal-content {
position: relative;
display: flex;
flex-direction: column;
justify-content: center;
margin: auto;
padding: 0 0 0 0;
width: 80%;
max-width: 1200px;
}
/* Same with your slides, you set the display to none, because you want to choose which
one is shown at a time. */
.slide {
display: none;
}
.image-slide {
width: 100%;
}
.modal-preview {
width: 100%;
}
.dots {
display: flex;
flex-direction: row;
justify-content: space-between;
}
/* You want the previews a little transparent to show that they are "inactive".
You then add an .active or :hover class to animate the selections for your user when
they interact with your controls and clickable content.
*/
img.preview, img.modal-preview {
opacity: 0.6;
}
img.active,
.preview:hover,
.modal-preview:hover {
opacity: 1;
}
img.hover-shadow {
transition: 0.3s;
}
.hover-shadow:hover {
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}
.close {
color: white;
position: absolute;
top: 10px;
right: 25px;
font-size: 35px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #999;
text-decoration: none;
cursor: pointer;
}
.previous,
.next {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
padding: 16px;
margin-top: -50px;
color: white;
font-weight: bold;
font-size: 20px;
transition: 0.6s ease;
border-radius: 0 3px 3px 0;
user-select: none;
-webkit-user-select: none;
}
.next {
right: 0;
border-radius: 3px 0 0 3px;
}
.previous:hover,
.next:hover {
background-color: rgba(0, 0, 0, 0.8);
}
```
### 第3步.JavaScript
现在去做生意您的JavaScript应如下所示
```javascript
// Initialize here and run showSlide() to give your lightbox a default state.
let slideIndex = 1;
showSlide(slideIndex);
// You are providing the functionality for your clickable content, which is
// your previews, dots, controls and the close button.
function openLightbox() {
document.getElementById('Lightbox').style.display = 'block';
}
function closeLightbox() {
document.getElementById('Lightbox').style.display = 'none';
};
// Note that you are assigning new values here to our slidIndex.
function changeSlide(n) {
showSlide(slideIndex += n);
};
function toSlide(n) {
showSlide(slideIndex = n);
};
// This is your logic for the light box. It will decide which slide to show
// and which dot is active.
function showSlide(n) {
const slides = document.getElementsByClassName('slide');
let modalPreviews = document.getElementsByClassName('modal-preview');
if (n > slides.length) {
slideIndex = 1;
};
if (n < 1) {
slideIndex = slides.length;
};
for (let i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
};
for (let i = 0; i < modalPreviews.length; i++) {
modalPreviews[i].className = modalPreviews[i].className.replace(' active', '');
};
slides[slideIndex - 1].style.display = 'block';
modalPreviews[slideIndex - 1].className += ' active';
};
```
这就是它!现在将所有代码放在一起。你现在应该有一个功能性的灯箱。
### 所有守则
```html
<body>
<style>
html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
body {
margin: 0;
}
.preview {
width: 100%;
}
.row {
display: flex;
flex-direction: row;
justify-content: space-between;
}
.row > .col {
padding: 0 8px;
}
.col {
float: left;
width: 25%;
}
.modal {
display: none;
position: fixed;
z-index: 1;
padding: 10px 62px 0px 62px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: black;
}
.modal-content {
position: relative;
display: flex;
flex-direction: column;
justify-content: center;
margin: auto;
padding: 0 0 0 0;
width: 80%;
max-width: 1200px;
}
.slide {
display: none;
}
.image-slide {
width: 100%;
}
.modal-preview {
width: 100%;
}
.dots {
display: flex;
flex-direction: row;
justify-content: space-between;
}
img.preview, img.modal-preview {
opacity: 0.6;
}
img.active,
.preview:hover,
.modal-preview:hover {
opacity: 1;
}
img.hover-shadow {
transition: 0.3s;
}
.hover-shadow:hover {
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}
.close {
color: white;
position: absolute;
top: 10px;
right: 25px;
font-size: 35px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #999;
text-decoration: none;
cursor: pointer;
}
.previous,
.next {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
padding: 16px;
margin-top: -50px;
color: white;
font-weight: bold;
font-size: 20px;
transition: 0.6s ease;
border-radius: 0 3px 3px 0;
user-select: none;
-webkit-user-select: none;
}
.next {
right: 0;
border-radius: 3px 0 0 3px;
}
.previous:hover,
.next:hover {
background-color: rgba(0, 0, 0, 0.8);
}
</style>
<div class="row">
<div class="col">
<img src="https://static.pexels.com/photos/385997/pexels-photo-385997.jpeg" onclick="openLightbox();toSlide(1)" class="hover-shadow preview" alt="Toy car on the road." />
</div>
<div class="col">
<img src="https://static.pexels.com/photos/574521/pexels-photo-574521.jpeg" onclick="openLightbox();toSlide(2)" class="hover-shadow preview" alt="Toy car exploring offroad." />
</div>
<div class="col">
<img src="https://static.pexels.com/photos/386009/pexels-photo-386009.jpeg" onclick="openLightbox();toSlide(3)" class="hover-shadow preview" alt="Toy car in the city" />
</div>
</div>
<div id="Lightbox" class="modal">
<span class="close pointer" onclick="closeLightbox()">&times;</span>
<div class="modal-content">
<div class="slide">
<img src="https://static.pexels.com/photos/385997/pexels-photo-385997.jpeg" class="image-slide" alt="Toy car on the road." />
</div>
<div class="slide">
<img src="https://static.pexels.com/photos/574521/pexels-photo-574521.jpeg" class="image-slide" alt="Toy car exploring offroad." />
</div>
<div class="slide">
<img src="https://static.pexels.com/photos/386009/pexels-photo-386009.jpeg" class="image-slide" alt="Toy car in the city." />
</div>
<a class="previous" onclick="changeSlide(-1)">&#10094;</a>
<a class="next" onclick="changeSlide(1)">&#10095;</a>
<div class="dots">
<div class="col">
<img src="https://static.pexels.com/photos/385997/pexels-photo-385997.jpeg" class="modal-preview hover-shadow" onclick="toSlide(1)" alt="Toy car on the road." />
</div>
<div class="col">
<img src="https://static.pexels.com/photos/574521/pexels-photo-574521.jpeg" class="modal-preview hover-shadow" onclick="toSlide(2)" alt="Toy car exploring offroad." />
</div>
<div class="col">
<img src="https://static.pexels.com/photos/386009/pexels-photo-386009.jpeg" class="modal-preview hover-shadow" onclick="toSlide(3)" alt="Toy car in the city" />
</div>
</div>
</div>
</div>
<script>
let slideIndex = 1;
showSlide(slideIndex);
function openLightbox() {
document.getElementById('Lightbox').style.display = 'block';
};
function closeLightbox() {
document.getElementById('Lightbox').style.display = 'none';
};
function changeSlide(n) {
showSlide(slideIndex += n);
};
function toSlide(n) {
showSlide(slideIndex = n);
};
function showSlide(n) {
const slides = document.getElementsByClassName('slide');
let modalPreviews = document.getElementsByClassName('modal-preview');
if (n > slides.length) {
slideIndex = 1;
};
if (n < 1) {
slideIndex = slides.length;
};
for (let i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
};
for (let i = 0; i < modalPreviews.length; i++) {
modalPreviews[i].className = modalPreviews[i].className.replace(' active', '');
};
slides[slideIndex - 1].style.display = 'block';
modalPreviews[slideIndex - 1].className += ' active';
};
</script>
</body>
```
## 更多信息:
#### HTML
[模态](https://en.wikipedia.org/wiki/Modal_window) - 弹出窗口
[事件处理程序](https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Event_handlers) - 侦听用户事件的HTML属性。
[实体](https://developer.mozilla.org/en-US/docs/Glossary/Entity) - 表示HTML中保留字符的字符串。
#### CSS
[box-sizing](https://css-tricks.com/box-sizing/) - 一个CSS3属性用于控制浏览器根据高度和宽度呈现内容的方式。
[Flex-box](https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Flexbox) - 一种新技术有助于在响应式操作中定位HTML内容。
[hover](https://developer.mozilla.org/en-US/docs/Web/CSS/:hover) - 当用户将一个元素悬停在元素上时会触发的伪选择器。
#### JavaScript的
[](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let)一个块范围变量。
[const](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const)一个块范围常量。
[getElementById](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById) - 一个返回对HTML元素的引用的文档方法。
[getElementsByClassName](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName) - 一个document方法它返回对具有匹配类的html的引用数组。
[\+ =](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators) - 一个赋值运算符,它将添加数字或连接字符串。
#### 资源:
[实例](https://codepen.io/rdev-rocks/pen/KXNzvo?editors=1111) - 用于演示上述代码的CodePen。
[交互式Flex-Box](https://codepen.io/enxaneta/full/adLPwv) - 一种显示弹性框行为的交互式CodePen。
[Pexels](https://www.pexels.com/) - 免费图片库。
[MDN](https://developer.mozilla.org/en-US/) - 关于网络信息的好地方。
[W3School - 灯箱](https://www.w3schools.com/howto/howto_js_lightbox.asp) - 此代码的灵感来自于此。谢谢W3Schools

View File

@ -0,0 +1,60 @@
---
title: How to Create a Slideshow
localeTitle: 如何创建幻灯片
---
## 如何创建幻灯片
Web幻灯片是一系列图像或文本它们在一个时间间隔中显示该序列的一个元素。
在本教程中,您可以按照以下步骤创建幻灯片:
### 写一个标记。
\`\`\`HTML 幻灯片
```
### Write styles to hide slides and show only one slide.
For hide the slides you have to give them a default style and only show one slide if this is active or you want to show it.
```
CSS \[data-component =“slideshow”\] .slide { displaynone; }
\[data-component =“slideshow”\] .slide.active { 显示:块; }
```
### Change the slides in a time interval.
The first step to change the slides to show, is select the slide wrapper(s) and then its slides.
When you selected the slides you have to go over each slide and add or remove an active class depending on the slide that you want to show, and then just repeat the process in a time interval.
Keep it in mind when you remove a active class to a slide, you are hidden it because the styles defined in the previous step. But when you add an active class to the slide, you are overwritring the style ``display:none to display:block`` , so the slide will show to the users.
```
JS var slideshows = document.querySelectorAll'\[data-component =“slideshow”\]';
//应用于您使用markup编写的所有幻灯片 slideshows.forEachinitSlideShow;
function initSlideShowslideshow{
```
var slides = document.querySelectorAll(`#${slideshow.id} [role="list"] .slide`); // Get an array of slides
var index = 0, time = 5000;
slides[index].classList.add('active');
setInterval( () => {
slides[index].classList.remove('active');
//Go over each slide incrementing the index
index++;
// If you go over all slides, restart the index to show the first slide and start again
if (index === slides.length) index = 0;
slides[index].classList.add('active');
}, time);
```
} \`\`\`
#### [本教程后面的Codepen示例](https://codepen.io/AndresUris/pen/rGXpvE)

View File

@ -0,0 +1,11 @@
---
title: How to Create a Top Navigation Bar
localeTitle: 如何创建顶部导航栏
---
## 如何创建顶部导航栏
这是一个存根。 [帮助我们的社区扩展它](https://github.com/freecodecamp/guides/tree/master/src/pages/javascript/tutorials/how-to-create-a-top-navigation-bar/index.md) 。
[这种快速风格指南有助于确保您的拉取请求被接受](https://github.com/freecodecamp/guides/blob/master/README.md) 。
#### 更多信息:

View File

@ -0,0 +1,11 @@
---
title: How to Create an Accordion
localeTitle: 如何创建手风琴
---
## 如何创建手风琴
这是一个存根。 [帮助我们的社区扩展它](https://github.com/freecodecamp/guides/tree/master/src/pages/javascript/tutorials/how-to-create-an-accordion/index.md) 。
[这种快速风格指南有助于确保您的拉取请求被接受](https://github.com/freecodecamp/guides/blob/master/README.md) 。
#### 更多信息:

View File

@ -0,0 +1,46 @@
---
title: How to Create Popups
localeTitle: 如何创建弹出窗口
---
## 如何创建弹出窗口
当您使用鼠标选择选项或按特殊功能键时,弹出窗口会弹出(显示)。
在此示例中当您单击按钮时将显示弹出窗口并且在您按下X选项之前将保持在屏幕上。
我们将使用`HTML` `CSS``JavaScript`构建弹出窗口
### 第1步HTML
HTML提供弹出窗口的结构
\`\`\`HTML
打开PopUp
弹出JavaScript
X
```
### Step 2 CSS
We will choose our own style for the popup window. Notice: the popup div should be hidden at first, so in the style I will select display: none;
```
CSS .popup _main_ div { 位置:固定; 宽度800px; 身高400px; 边框2px纯黑色; border-radius5px; background-color#fff; 左50; margin-left-400px; 最高50; margin-top-250px; displaynone;
} .close _popup { 位置:绝对; 宽度25px; 身高25px; border-radius25px; 边框2px纯黑色; text-aligncenter; 右5px; 上5px; 游标:指针; } .close_ popup p { margin-top5px; font-weight400;
} 。文本{ text-aligncenter; font-size30px; font-weight400; 保证金最高22; } #Btn { 位置:绝对; 左50; 顶部20;
}
```
### Step 3 JavaScript
```
JS //首先,我将初始化我的变量 //选择我们将从DOM中使用的元素 //我将在按钮中添加en事件该事件将触发一个函数将弹出窗口的显示样式从none更改为block
const Btn = document.getElementById“Btn” const PopupDiv = document.querySelector“。popup _main_ div” const ClosePopup = document.querySelector“。close\_popup” Btn.addEventListener '点击',函数(){ PopupDiv.style.display = “块” } ClosePopup.addEventListener '点击',函数(){ PopupDiv.style.display = “无” }
\`\`\`
实时代码: [Codepen.io](https://codepen.io/voula12/pen/qyyNeK)

View File

@ -0,0 +1,11 @@
---
title: How to Create Tabs
localeTitle: 如何创建选项卡
---
## 如何创建选项卡
这是一个存根。 [帮助我们的社区扩展它](https://github.com/freecodecamp/guides/tree/master/src/pages/javascript/tutorials/how-to-create-tabs/index.md) 。
[这种快速风格指南有助于确保您的拉取请求被接受](https://github.com/freecodecamp/guides/blob/master/README.md) 。
#### 更多信息:

View File

@ -0,0 +1,32 @@
---
title: How to Install Node Js and Npm on Windows
localeTitle: 如何在Windows上安装Node Js和Npm
---
## 如何在Windows上安装Node Js和Npm
在Windows上安装Node.js和Npm非常简单。
首先,从[Node.js网站](https://nodejs.org/)下载Windows安装程序。您可以选择**LTS** (长期支持)或**当前**版本。
* **当前**版本可以更快地接收最新功能和更新
* **LTS**版本具有更改以提高稳定性,但会收到错误修复和安全更新等补丁
选择满足需求的版本后,请运行安装程序。按照提示选择安装路径,并确保包含**npm包管理器**功能以及**Node.js运行时** 。这应该是默认配置。
安装完成后重新启动计算机。
如果您在默认配置下安装现在应将Node.js添加到PATH中。运行命令提示符或powershell并输入以下内容进行测试
```
> node -v
```
控制台应响应版本字符串。为Npm重复这个过程
```
> npm -v
```
如果两个命令都有效那么您的安装就会成功您可以开始使用Node.js
#### 更多信息:
有关更多信息和指南,请访问[Node.js文档页面](https://nodejs.org/en/docs/) 。

View File

@ -0,0 +1,15 @@
---
title: Increment a Number with JavaScript
localeTitle: 使用JavaScript增加数字
---
您可以使用`++`运算符轻松地为变量增加或添加`1`
```
i++;
```
相当于
```
i = i + 1;
```
**注意**整行成为`i++;` ,消除了对等号的需要。

View File

@ -0,0 +1,11 @@
---
title: Tutorials
localeTitle: 教程
---
## 教程
这是一个存根。 [帮助我们的社区扩展它](https://github.com/freecodecamp/guides/tree/master/src/pages/javascript/tutorials/index.md) 。
[这种快速风格指南有助于确保您的拉取请求被接受](https://github.com/freecodecamp/guides/blob/master/README.md) 。
#### 更多信息:

View File

@ -0,0 +1,7 @@
---
title: Invert Regular Expression Matches with JavaScript
localeTitle: 使用JavaScript反转正则表达式匹配
---
使用`/\S/gi` ;匹配字符串中不是空格的所有内容。
您可以通过使用选择的大写版本反转任何匹配`\s``\S`的例子。

View File

@ -0,0 +1,26 @@
---
title: Iterate with JavaScript for Loops
localeTitle: 使用JavaScript迭代循环
---
JavaScript的循环的最常见的类型被称为`for loop` ,因为它运行`for`的特定次数。
```
var ourArray = [];
for(var i = 0; i < 5; i++) {
ourArray.push(i);
}
```
ourArray现在包含\[0,1,2,3,4\]
## 更多关于for循环
```
for(var i = 0; i < 5; i++) { // There are 3 parts here
```
循环有三个部分。它们用分号分隔。
1. 初始化: `var i = 0;` - 此代码仅在循环开始时运行一次。它通常用于声明计数器变量(使用`var` 并初始化计数器在这种情况下它设置为0
2. 条件: `i < 5;` - 只要这是`true` ,循环就会运行。这意味着只要`i`等于5循环就会停止循环。请注意循环内部永远不会将`i`视为5因为它将在此之前停止。如果此条件最初为`false` ,则循环将永远不会执行。
3. 增量: `i++` - 此代码在每个循环结束时运行。它通常是一个简单的增量( `++`运算符),但实际上可以是任何数学变换。它用于向前移动计数器( `i` )(或向后移动等)。

View File

@ -0,0 +1,14 @@
---
title: Iterate with JavaScript While Loops
localeTitle: 在循环时使用JavaScript进行迭代
---
另一种类型的JavaScript循环称为`while loop`因为它`while`某些内容为true时运行并在某些内容不再为true时停止。
```
var ourArray = [];
var i = 0;
while(i < 5) {
ourArray.push(i);
i++;
}
```

View File

@ -0,0 +1,43 @@
---
title: JavaScript for Loops Explained
localeTitle: 用于循环的JavaScript解释
---
for语句创建一个循环该循环由三个可选表达式组成括在括号中并用分号分隔后跟循环中执行的语句或一组语句。
for循环具有以下语法
```
for (<a href='http://forum.freecodecamp.com/t/javascript-while-loop/14668' target='_blank' rel='nofollow'>initialization]; [condition]; [final-expression]) {
code block to be executed
}
```
在循环(代码块)开始之前执行\[初始化\]。
\[condition\]定义运行循环的条件(代码块)。
每次执行循环(代码块)后执行\[final-expression\]。
## JavaScript中的示例
```
var ourArray = [];
for (var i = 0; i < 5; i++) {
ourArray.push(i);
}
```
从上面的示例中,您可以阅读:
\[initialization\]在循环开始之前设置变量var i = 0
\[condition\]定义循环运行的条件i必须小于5
\[final-expression\]每次执行循环中的代码块时都会增加一个值i ++)。
## 为什么我们需要“for循环”
for循环用于循环遍历代码块已知次数。有时它是计算机知道多少次而不是你但它仍然是已知的。
查看我们关于循环的其他一些文章:
* \[而Loop
* [对于In Loop](http://forum.freecodecamp.com/t/javascript-for-in-loop/14665)

View File

@ -0,0 +1,59 @@
---
title: Page Redirects Using JavaScript
localeTitle: 页面重定向使用JavaScript
---
## 页面重定向使用JavaScript
如果您尝试将用户重定向到另一个页面则可以轻松使用JavaScript来完成此任务。请务必注意以下事项
即使您在脚本中加载了jQuery库您也可能希望将纯JavaScript解决方案用于页面重定向以提高效率。
有几种不同的方法可以解决这个问题,但最简单的方法是使用`window.location`对象将用户发送到您希望将其重定向到的页面。所述`window.location`对象可以使用任何有效的URL值如`http://www.yoururl.com` `somepage.html`
```javascript
window.location = 'http://www.yoururl.com';
// window.location = 'somepage.html';
// etc.
```
### 特殊情况重定向
您可以使用特殊的重定向方法,默认情况下,该方法附加到名为`replace()`每个主要浏览器中的`window.location`对象。此方法接受与仅使用`window.location`相同的有效URL值。
下面是使用此方法的示例(它仍然与在其他浏览器中使用`window.location`相同):
```javascript
window.location.replace('http://www.yoururl.com');
// window.location.replace('somepage.html');
// etc.
```
### 使用JS进行简单的定时重定向
以下是使用`setTimeout()`函数进行简单定时重定向的示例。定时重定向非常有用,您可以通过重定向页面上的内容向用户解释将其重定向到另一个页面的原因。
```javascript
// the 5000 below is 5000 milliseconds which equals 5 seconds until the redirect happens
// keep in mind that 1 second = 1000 milliseconds
setTimeout(function () {
window.location = 'http://www.yoururl.com';
// window.location = 'somepage.html';
// etc.
}, 5000);
```
### 倒退
有时用户在禁用JavaScript的情况下浏览互联网这显然会带来JS依赖重定向解决方案的问题。我建议设置一个`<meta>`元素它将使用新位置刷新浏览器。我应该在JS重定向发生后将这个元素设置为秒。因此如果您在5秒后在JS中发生重定向请将`<meta>`元素重定向设置为6秒。
`<meta>`元素放在文档的`<head>` ,如下所示:
```html
<head>
<!-- Change the 6 below to however many seconds you wish to wait until redirection to the new page. Change the portion after "URL=" to the URL of your choice. This can be a local page: URL=somepage.html, a web address: URL=http://www.yoururl.com, or any other valid URL. It is important to note the semicolon between the number of seconds to refresh and the URL. -->
<meta http-equiv="refresh" content="6;URL=http://www.yoururl.com">
</head>
```
请记住,并非所有浏览器都支持`<meta>`元素我正在看你IE的旧版本和Safari但大多数现代浏览器都支持Microsoft Edge谷歌浏览器Mozilla FirefoxOpera

View File

@ -0,0 +1,9 @@
---
title: Perform Arithmetic Operations on Decimals with JavaScript
localeTitle: 使用JavaScript对小数执行算术运算
---
在JavaScript中您可以使用十进制数执行计算就像整数一样。
```
var quotient = 4.4 / 2.0; // equals 2.2
```

View File

@ -0,0 +1,12 @@
---
title: Store Multiple Values in One Variable Using JavaScript Arrays
localeTitle: 使用JavaScript数组在一个变量中存储多个值
---
使用JavaScript数组变量我们可以在一个地方存储多个数据。
你用一个开括号开始一个数组声明,用一个右括号结束它,并在每个条目之间加一个逗号,如下所示:
```
var sandwich = ["peanut butter", "jelly", "bread"]
```
`myArray = [2,'j'];`

View File

@ -0,0 +1,11 @@
---
title: Subtract One Number from Another with JavaScript
localeTitle: 使用JavaScript从另一个数字中减去一个数字
---
我们也可以从另一个数字中减去一个数字。
JavaScript使用 - 符号进行减法。
```
var difference = 45 - 33;
```

View File

@ -0,0 +1,70 @@
---
title: JavaScript Version of Jquerygetjson
localeTitle: Jquerygetjson的JavaScript版本
---
如果你想使用只有vanilla JavaScript的json文件。
## IE8 +
```
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);
request.onreadystatechange = function() {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
// Success!
var data = JSON.parse(this.responseText);
} else {
// Error :(
}
}
};
request.send();
request = null;
```
## IE9 +
```
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
var data = JSON.parse(request.responseText);
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
```
## IE10 +
```
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
// Success!
var data = JSON.parse(this.response);
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
```

View File

@ -0,0 +1,20 @@
---
title: Use the JavaScript Console
localeTitle: 使用JavaScript控制台
---
Chrome和Firefox都有出色的JavaScript控制台也称为DevTools用于调试JavaScript。
您可以在Chrome的菜单或FireFox菜单中的Web控制台中找到开发人员工具。如果您使用的是其他浏览器或手机我们强烈建议您使用桌面版Firefox或Chrome。
您还可以使用[https://repl.it/](https://repl.it/)在线运行代码。
这是您打印到控制台的方式:
```
console.log('Hello world!')
```
您还可以使用以下代码在控制台中打印错误日志:
```
console.error('I am an error!')
```

View File

@ -0,0 +1,80 @@
---
title: Using Anonymous Functions for Private Namespacing in Your JavaScript Apps
localeTitle: 在JavaScript应用程序中使用匿名函数进行私有命名空间
---
让我们来看看构建JavaScript应用程序时命名空间的含义以及构建应用程序时使用私有命名空间的一些好处。
**请注意本文引用了匿名自执行函数。如果你不知道这是什么请阅读Noah Stokes的这篇优秀文章 [自我执行匿名函数或如何编写干净的Javascript](http://esbueno.noahstokes.com/post/77292606977/self-executing-anonymous-functions-or-how-to-write) 。本文将详细介绍匿名自执行函数。**
## 什么是命名空间?
简而言之命名空间只是一段具有自己空间的代码。当您第一次开始编写JS应用程序时通常只需键入代码并运行它。这将所有代码放入所谓的**全局命名空间** ,其中包含您正在使用的窗口的所有代码。
但是,如果将所有代码保存在**全局命名空间中** 则可能会遇到冲突命名约定等问题尤其是在大型JS应用程序/游戏中。
让我们来看一个如何仅使用**全局命名空间**来开发游戏的例子。
所以,假设我们有一款游戏可以跟踪玩家拥有的点数:
```
var points = 0;
```
许多游戏跟踪点以增加游戏的竞争优势。只需在脚本中键入该行我们就创建了一个名为_points_的变量可以跟踪用户获得的点数。
这一切都很好但是让我们说我们有一个更高级的用户玩游戏。这个用户知道如何查看网页的来源因此这个人看一看JS游戏背后的源并意识到_points_变量只是坐在**全局命名空间中** 。当他们思考他们可以达到的分数时一个邪恶的假笑在他们的脸上下降他们认为他们不想等到打败一些坏人或者粉碎一些蘑菇或者你有什么东西以获得一堆积分。他们现在想要他们的积分如何_发出数千亿亿_点的声音因此他们在自己喜欢的浏览器上加载控制台只需输入控制台
```
points = 34750925489459203859095480917458059034;
```
一旦用户点击进入, _点数_变量就会在游戏中更新。现在用户在游戏中有一个真正巨大的可能不切实际的积分他可以向他的朋友吹嘘没有人可以击败他的超棒成绩。
那么,我们如何防止这种情况发生?这是**私有命名空间**发挥作用的地方。
## 私有命名空间
**私有命名空间**允许开发人员将他们的代码放入部分(或**命名空间** )。这些部分彼此独立运行,但仍可以从**全局命名空间**读取和写入。
为了将其简化为现实生活中的简单术语,假设您正在办公楼中工作。你有自己的办公室,你看到其他人有自己的办公室。每个办公室都被锁定,只有拥有办公室的人才有办公室的钥匙。让我们也说你有一些新的超级锁定,使你的办公室难以被建筑物中的任何其他人穿透。让我们将办公楼本身视为**全局命名空间** ,将每个办公室视为**私有命名空间** 。您无权访问任何其他人的办公室,也无权访问您的办公室。但是,你们每个人都可以访问办公楼的其他部分,无论是喝咖啡,吃点心等等。你们每个人都可以从**全局命名空间中**获取东西(或者在那里创建/修改某些东西),但你可以从彼此的办公室创建/修改/抓取任何东西;您只能从自己的**私有命名空间** /办公室创建/修改/抓取。
## 实现私有命名空间
那么我们如何在JavaScript中实现这个**私有命名空间**呢使用匿名自执行功能如果您没有阅读Noah Stokes [自执行匿名函数或如何编写清洁Javascript的文章](http://esbueno.noahstokes.com/post/77292606977/self-executing-anonymous-functions-or-how-to-write) ,请立即执行此操作。本文将详细介绍匿名自执行函数。
让我们看看使用前面的那个_点_变量但是让我们把它分成一个**私有命名空间**
```
//The most common way you'll see an anonymous self-executing function
(function () {
var points = 0;
})();
//This is just one of many more alternative ways to use an anonymous self-executing function
/*
!function () {
var points = 0;
}();
*/
```
现在当用户访问该页面时他们将无法在浏览器中打开控制台并根据需要更改points变量的值真棒
## 命名空间和文档交互
上面的代码仅用于使用匿名自执行函数为代码提供自己的**私有命名空间** 。请记住名称空间只影响JS代码变量/数组/对象/等),而不影响与文档本身相关的代码。
命名空间中的任何代码仍然具有与HTML文档和CSS相同的访问权限就像通常在**全局命名空间中一样** 。看看接下来的两个代码示例。它们都执行相同的功能,并且既不比另一个更有益,也更有效。
```
<script type="text/javascript">
(function () {
document.querySelector('body').style.background = 'blue';
})();
</script>
```
是相同的:
```
<script type="text/javascript">
document.querySelector('body').style.background = 'blue';
</script>
```
请记住这只是在JavaScript应用程序中使用命名空间的一种方法。使您的代码适应最适合当前情况的代码。

View File

@ -0,0 +1,90 @@
---
title: What Does JavaScript Void 0 Mean
localeTitle: JavaScript无效0意味着什么
---
## JavaScript无效0意味着什么
**JavaScript的void运算符计算表达式并返回undefined**
使用控制台验证相同: -
![ConsoleOutput](https://github.com/srawat19/-Guide_Images/blob/master/VoidConsole.PNG?raw=true)
**_注意_** -不管**空隙**沿通过的任何值的, _如上所示总是返回**未定义**_ 。 但是, **操作数0的空格是首选**
**使用操作数0的两种方法 - > void0或void 0.**它们中的任何一个都可以。
#### 何时使用Javascript void0
单击链接时您不希望浏览器加载新页面或刷新同一页面具体取决于指定的URL。 而是执行附加到该链接的JavaScript。
#### 使用Javascript void0的示例示例1
```html
<html>
<body>
<a href="javascript:void(0);alert('Hello ! I am here')">Click Me</a>
</body>
</html>
```
#### 输出:
单击ClickMe链接时会弹出如下警告
![输出1](https://github.com/srawat19/-Guide_Images/blob/master/voidOutput1.PNG?raw=true)
#### 使用Javascript void0的示例示例2
```html
<html>
<body>
<a href="javascript:void(0)" ondblclick="alert('Hi,i didnt refresh the page')" )>Click Me</a>
</body>
</html>
```
#### 输出:
双击链接时,将弹出警报而不刷新任何页面。
#### 使用Javascript void0的示例示例3
```html
<html>
<body>
<a href="javascript:void(0);https://www.google.co.in/"
ondblclick="alert('Hello !! You will see me and not get redirected to google.com ')">Click Me</a>
</body>
</html>
```
#### 输出:
当您双击该链接时会弹出一个提醒关闭它也不会重定向到google.com。
#### 没有Javascript的示例示例void0
```html
<html>
<body>
<a href="https://www.google.co.in/" ondblclick="alert('Hello !! You will see me and then get redirected to google.com even if not needed')">Click Me</a>
</body>
</html>
```
#### 输出:
当您双击该链接时将弹出一个提醒关闭它将重定向到google.com。
#### 结论:
当您需要阻止任何不需要的页面刷新或重定向时, **void**运算符非常有用。 相反执行一些JavaScript操作。
#### 更多信息:
1 [Mozilla Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void) 2 [了解void 0](https://www.quackit.com/javascript/tutorial/javascript_void_0.cfm)

View File

@ -0,0 +1,33 @@
---
title: Write Reusable JavaScript with Functions
localeTitle: 用函数编写可重用的JavaScript
---
在JavaScript中我们可以将代码划分为称为函数的可重用部分。
这是一个函数的例子:
```
function functionName() {
console.log("Hello World");
}
```
您可以使用其名称后跟括号来`call``invoke`此函数,如下所示:
```
functionName();
```
每次调用该函数时它都会在开发控制台上打印出“Hello World”消息。每次调用函数时都会执行大括号之间的所有代码。
这是另一个例子:
```
function otherFunctionName (a, b) {
return(a + b);
}
```
我们可以像这样`call``invoke`我们的函数:
```
otherFunctionName(1,2);
```
它将运行并将其返回值返回给我们。