简介
什么是JavaScript?
Javascript是一种动态计算机编程语言。 它是轻量级的,最常用作网页的一部分,其实现允许客户端脚本与用户交互并生成动态页面。 它是一种具有面向对象功能的解释型编程语言。
JavaScript最初被称为LiveScript,但Netscape将其名称更改为JavaScript,可能是因为Java产生的兴奋。 JavaScript于1995年首次出现在Netscape 2.0中,名为LiveScript。 该语言的通用核心已嵌入Netscape,Internet Explorer和其他Web浏览器中。
ECMA-262规范定义了核心JavaScript语言的标准版本。
- JavaScript是一种轻量级的解释型编程语言。
- 专为创建以网络为中心的应用程序而设计。
- 与Java互补并与Java集成。
- HTML的补充和集成。
- 开放和跨平台
客户端JavaScript
客户端JavaScript是该语言最常见的形式。 该脚本应包含在HTML文档中或由HTML文档引用,以便浏览器解释代码。
这意味着网页不必是静态HTML,但可以包括与用户交互,控制浏览器以及动态创建HTML内容的程序。
JavaScript客户端机制提供了许多优于传统CGI服务器端脚本的优势。 例如,您可以使用JavaScript来检查用户是否在表单字段中输入了有效的电子邮件地址。
当用户提交表单时执行JavaScript代码,并且只有当所有条目都有效时,才会将它们提交给Web服务器。
JavaScript可用于捕获用户启动的事件,例如按钮单击,链接导航以及用户显式或隐式启动的其他操作。
JavaScript的优点
使用JavaScript的优点是 –
- 减少服务器交互 – 您可以在将页面发送到服务器之前验证用户输入。 这样可以节省服务器流量,这意味着服务器负载更少。
- 立即反馈给访问者 – 他们不必等待页面重新加载,看他们是否忘记输入内容。
- 增强交互性 – 您可以创建界面,当用户使用鼠标悬停它们或通过键盘激活它们时会做出反应。
- 更丰富的界面 – 您可以使用JavaScript来包含诸如拖放组件和滑块之类的项目,以便为您的站点访问者提供丰富的界面。
JavaScript的局限性
我们不能将JavaScript视为一种成熟的编程语言。 它缺乏以下重要功能 –
- 客户端JavaScript不允许读取或写入文件。 这是出于安全原因而保留的。
- JavaScript不能用于网络应用程序,因为没有这样的支持。
- JavaScript没有任何多线程或多处理器功能。
- JavaScript是一种轻量级的解释型编程语言,它允许您在其他静态HTML页面中构建交互性。
JavaScript开发工具
JavaScript的主要优势之一是它不需要昂贵的开发工具。您可以从简单的文本编辑器(如记事本)开始。由于它是Web浏览器上下文中的解释语言,因此您甚至不需要购买编译器。
为了让我们的生活更简单,各种供应商都提出了非常好的JavaScript编辑工具。其中一些列在这里 –
- Microsoft FrontPage – Microsoft开发了一个名为FrontPage的流行HTML编辑器。 FrontPage还为Web开发人员提供了许多JavaScript工具,以帮助创建交互式网站。
- Macromedia Dreamweaver MX – Macromedia Dreamweaver MX是专业Web开发人群中非常流行的HTML和JavaScript编辑器。它提供了几个方便的预构建JavaScript组件,与数据库完美集成,并符合XHTML和XML等新标准。
- Macromedia HomeSite 5 – HomeSite 5是Macromedia广受欢迎的HTML和JavaScript编辑器,可用于有效管理个人网站。
今天的JavaScript在哪里?
ECMAScript Edition 5标准将是四年多来发布的第一个更新。 JavaScript 2.0符合ECMAScript标准的第5版,两者之间的差异非常小。
可以在以下站点上找到JavaScript 2.0的规范:http://www.ecmascript.org/
今天,Netscape的JavaScript和Microsoft的JScript符合ECMAScript标准,尽管这两种语言仍然支持不属于标准的功能。
语法
Javascript 语法
JavaScript可以使用放在<script> … </script>中的JavaScript语句来实现。
您可以将包含JavaScript的<script>标记放在网页的任何位置,但通常建议您将其保留在<head>标记内。
<script>标记警告浏览器程序开始将这些标记之间的所有文本解释为脚本。 JavaScript的简单语法如下所示。
<script ...> JavaScript code </script>
脚本标记有两个重要属性 –
- 语言 – 此属性指定您正在使用的脚本语言。 通常,它的值将是javascript。虽然最近版本的HTML(和XHTML,它的继任者)已经逐步淘汰了这个属性的使用。
- 类型 – 此属性现在建议用于指示正在使用的脚本语言,其值应设置为“text/javascript”。
所以你的JavaScript片段看起来像 –
<script language="javascript" type="text/javascript"> JavaScript code </script>
你的第一个JavaScript脚本
让我们举一个示例来打印出“Hello World”。 我们添加了一个围绕JavaScript代码的可选HTML注释。 这是为了从不支持JavaScript的浏览器中保存我们的代码。 评论以“// – >”结尾。 这里“//”表示JavaScript中的注释,因此我们添加它以防止浏览器将HTML注释的末尾作为一段JavaScript代码读取。 接下来,我们调用一个函数document.write,它将一个字符串写入我们的HTML文档。
此函数可用于编写文本,HTML或两者。 看看下面的代码。
<html> <body> <script language="javascript" type="text/javascript"> <!-- document.write("Hello World!") //--> </script> </body> </html>
此代码将产生以下结果 –
Hello World!
空白和换行
JavaScript忽略JavaScript程序中出现的空格,制表符和换行符。 您可以在程序中自由使用空格,制表符和换行符,并且可以自由地以简洁一致的方式格式化和缩进程序,使代码易于阅读和理解。
分号是可选的
JavaScript中的简单语句通常后跟分号字符,就像它们在C,C ++和Java中一样。 但是,如果每个语句都放在一个单独的行上,则JavaScript允许您省略此分号。 例如,以下代码可以不带分号编写。
<script language="javascript" type="text/javascript"> <!-- var1 = 10 var2 = 20 //--> </script>
但是,如果在单行中格式化如下,则必须使用分号 −
<script language="javascript" type="text/javascript"> <!-- var1 = 10; var2 = 20; //--> </script>
注 − 使用分号是一种很好的编程习惯。
区分大小写
JavaScript是一种区分大小写的语言。 这意味着语言关键字,变量,函数名称和任何其他标识符必须始终使用一致的字母大小写。
因此标识符Time和TIME将在JavaScript中传达不同的含义。
注 – 在JavaScript中编写变量和函数名称时应小心。
JavaScript中的注释
JavaScript支持C风格和C ++风格的注释,因此 –
- //和行尾之间的任何文本都被视为注释,并被JavaScript忽略。
- 字符/*和*/之间的任何文本都被视为注释。 这可能跨越多行。
- JavaScript还识别HTML注释开放序列<!–。 JavaScript将此视为单行注释,就像//注释一样。
- JavaScript无法识别HTML注释结束序列–>,因此应将其写为//–>。
例子
<script language="javascript" type="text/javascript"> <!-- // This is a comment. It is similar to comments in C++ /* * This is a multiline comment in JavaScript * It is very similar to comments in C Programming */ //--> </script>
配置
在浏览器中启用JavaScript
所有现代浏览器都内置了对JavaScript的支持。 通常,您可能需要手动启用或禁用此支持。 本章介绍在浏览器中启用和禁用JavaScript支持的过程:Internet Explorer,Firefox,Chrome和Opera。
Internet Explorer中的JavaScript
以下是在Internet Explorer中打开或关闭JavaScript的简单步骤 –
- 从菜单中按工具→Internet选项。
- 从对话框中选择“安全”选项卡。
- 单击“自定义级别”按钮。
- 向下滚动,直到找到“脚本”选项。
- 选择活动脚本下的启用单选按钮。
- 最后点击OK然后出来。
要在Internet Explorer中禁用JavaScript支持,您需要在“活动脚本”下选择“禁用”单选按钮。
Firefox中的JavaScript
以下是在Firefox中打开或关闭JavaScript的步骤 –
- 打开新标签→在地址栏中输入about:config。
- 然后你会找到警告对话框。 选择我会小心,我保证!
- 然后,您将在浏览器中找到配置选项列表。
- 在搜索栏中输入javascript.enabled。
- 在那里,您可以通过右键单击该选项的值来选择启用或禁用javascript→选择切换。
如果javascript.enabled为true; 点击toogle后,它会转换为false。 如果javascript被禁用; 单击切换后启用它。
Chrome中的JavaScript
以下是在Chrome中打开或关闭JavaScript的步骤 –
- 点击浏览器右上角的Chrome菜单。
- 选择设置。
- 单击页面末尾的“显示高级设置”。
- 在“隐私”部分下,单击“内容设置”按钮。
- 在“Javascript”部分中,选择“不允许任何网站运行JavaScript”或“允许所有网站运行JavaScript(推荐)”。
Opera中的JavaScript
以下是在Opera中打开或关闭JavaScript的步骤 –
- 从菜单中按工具→首选项。
- 从对话框中选择“高级”选项。
- 从列出的项目中选择内容。
- 选择启用JavaScript复选框。
- 最后点击OK然后出来。
要在Opera中禁用JavaScript支持,请不要选中“启用JavaScript”复选框。
非JavaScript浏览器的警告
如果您必须使用JavaScript执行重要操作,则可以使用<noscript>标记向用户显示警告消息。
你可以在脚本块之后立即添加一个noscript块,如下所示 –
<html> <body> <script language="javascript" type="text/javascript"> <!-- document.write("Hello World!") //--> </script> <noscript> Sorry...JavaScript is needed to go ahead. </noscript> </body> </html>
现在,如果用户的浏览器不支持JavaScript或未启用JavaScript,则来自的消息将显示在屏幕上。
放置
JavaScript – HTML文件中的放置
可以灵活地在HTML文档中的任何位置包含JavaScript代码。 但是,在HTML文件中包含JavaScript的最佳方法如下 −
- Script在<head>…</head>中。
- Script在<body>…</body>中。
- Script在<body>…</body> and <head>…</head>中。
- Script在外部文件中编写脚本,<head>…</head>中。
在下一节中,我们将了解如何以不同方式将JavaScript放入HTML文件中。
JavaScript在<head>…</head>中
如果您希望在某个事件上运行脚本,例如当用户单击某个位置时,则会将该脚本放在头部中,如下所示 −
<html> <head> <script type="text/javascript"> <!-- function sayHello() { alert("Hello World") } //--> </script> </head> <body> <input type="button" onclick="sayHello()" value="Say Hello" /> </body> </html>
此代码将产生以下结果 −
Hello World
JavaScript在<body>…</body>中
如果您需要在页面加载时运行脚本以便脚本在页面中生成内容,那么脚本将进入&lt; body&gt; 文件的一部分。 在这种情况下,您将不会使用JavaScript定义任何函数。 看看下面的代码。
<html> <head> </head> <body> <script type="text/javascript"> <!-- document.write("Hello World") //--> </script> <p>This is web page body </p> </body> </html>
此代码将产生以下结果 −
Hello World This is web page body
JavaScript在 <body> and <head>中
你可以放Javascrpit代码在 <head> and <body>中,如下−
<html> <head> <script type="text/javascript"> <!-- function sayHello() { alert("Hello World") } //--> </script> </head> <body> <script type="text/javascript"> <!-- document.write("Hello World") //--> </script> <input type="button" onclick="sayHello()" value="Say Hello" /> </body> </html>
此代码将产生以下结果 −
Hello World
JavaScript在外部文件
当您开始更广泛地使用JavaScript时,您可能会发现有些情况下您在网站的多个页面上重复使用相同的JavaScript代码。
您不限于在多个HTML文件中维护相同的代码。 脚本标记提供了一种机制,允许您将JavaScript存储在外部文件中,然后将其包含在HTML文件中。
下面是一个示例,说明如何使用脚本标记及其src属性在HTML代码中包含外部JavaScript文件。
<html> <head> <script type="text/javascript" src="filename.js" ></script> </head> <body> ....... </body> </html>
要使用外部文件源中的JavaScript,您需要在扩展名为“.js”的简单文本文件中编写所有JavaScript源代码,然后包含该文件,如上所示。
例如,您可以在filename.js文件中保留以下内容,然后在包含filename.js文件后,可以在HTML文件中使用sayHello函数。
function sayHello() { alert("Hello World") }
变量
JavaScript数据类型
编程语言最基本的特征之一是它支持的数据类型集。 这些是可以用编程语言表示和操作的值的类型。
JavaScript允许您使用三种原始数据类型 −
- Numbers, 例如 123, 120.50 等.
- Strings 例如 “This text string” 等.
- Boolean 例如 true or false.
JavaScript还定义了两个简单的数据类型,null和undefined,每个数据类型只定义一个值。 除了这些原始数据类型之外,JavaScript还支持称为对象的复合数据类型。 我们将在单独的章节中详细介绍对象。
注 – JavaScript不区分整数值和浮点值。 JavaScript中的所有数字都表示为浮点值。 JavaScript使用IEEE 754标准定义的64位浮点格式表示数字。
JavaScript变量
像许多其他编程语言一样,JavaScript也有变量。 变量可以被认为是命名容器。 您可以将数据放入这些容器中,然后只需命名容器即可引用数据。
在JavaScript程序中使用变量之前,必须声明它。 使用var关键字声明变量,如下所示。
<script type="text/javascript"> <!-- var money; var name; //--> </script>
您还可以使用相同的var关键字声明多个变量,如下所示 −
<script type="text/javascript"> <!-- var money, name; //--> </script>
在变量中存储值称为变量初始化。 您可以在变量创建时或在需要该变量的稍后时间点进行变量初始化。
例如,您可以创建一个名为money的变量,并在以后为其分配值2000.50。 对于另一个变量,您可以在初始化时分配一个值,如下所示。
<script type="text/javascript"> <!-- var name = "Ali"; var money; money = 2000.50; //--> </script>
注 – 对于声明或初始化,只使用var关键字,对于文档中任何变量名的生命周期。 您不应该两次重新声明相同的变量。
JavaScript是无类型语言。 这意味着JavaScript变量可以保存任何数据类型的值。 与许多其他语言不同,您不必在变量声明期间告诉JavaScript变量将包含哪种类型的值。 变量的值类型可以在程序执行期间更改,JavaScript会自动处理它。
JavaScript变量作用域
变量的作用域是程序中定义它的区域。 JavaScript变量只有两个范围。
- 全局变量 − 全局变量具有全局范围,这意味着它可以在JavaScript代码中的任何位置定义。
- 局部变量 − 局部变量仅在定义它的函数中可见。 函数参数始终是该函数的本地参数。
在函数体内,局部变量优先于具有相同名称的全局变量。 如果声明一个与全局变量同名的局部变量或函数参数,则可以有效地隐藏全局变量。 请看下面的示例。
<html> <body onload = checkscope();> <script type = "text/javascript"> <!-- var myVar = "global"; // Declare a global variable function checkscope( ) { var myVar = "local"; // Declare a local variable document.write(myVar); } //--> </script> </body> </html>
这产生以下结果 −
local
JavaScript变量命名规则
在JavaScript中命名变量时,请记住以下规则。
- 您不应将任何JavaScript保留关键字用作变量名称。 这些关键字将在下一节中提到。 例如,break或boolean变量名称无效。
- JavaScript变量名称不应以数字(0-9)开头。 它们必须以字母或下划线字符开头。 例如,123test是无效的变量名称,但_123test是有效的。
- JavaScript变量名称区分大小写。 例如,Name和name是两个不同的变量。
JavaScript保留字
下表给出了JavaScript中所有保留字的列表。 它们不能用作JavaScript变量,函数,方法,循环标签或任何对象名称。
abstract | else | instanceof | switch |
boolean | enum | int | synchronized |
break | export | interface | this |
byte | extends | long | throw |
case | false | native | throws |
catch | final | new | transient |
char | finally | null | true |
class | float | package | try |
const | for | private | typeof |
continue | function | protected | var |
debugger | goto | public | void |
default | if | return | volatile |
delete | implements | short | while |
do | import | static | with |
double | in | super |
操作符
什么是运算符?
让我们采用一个简单的表达式4 + 5等于9.这里4和5被称为操作数,’+’被称为运算符。 JavaScript支持以下类型的运算符。
- 算术运算符
- 比较运算符
- 逻辑(或关系)运算符
- 赋值运算符
- 条件(或三元)运算符
算术运算符
JavaScript支持以下算术运算符 –
假设变量A保持10,变量B保持20,则−
序号 | 运算符和描述 |
---|---|
1 | + (加) 加2个数 例如:A + B = 30 |
2 | – (减) 从第一个中减去第二个操作数 例如:A – B = -10 |
3 | * (乘) 两个数相乘 例如: A * B = 200 |
4 | / (除) 用分母除以分子 例如: B/A = 2 |
5 | % (求余数) 输出整数除法的余数 例如: B % A = 0 |
6 | ++ (自增) 将整数值增加1 例如: A++ = 11 |
7 | — (自减) 将整数值减1 例如: A– = 9 |
注 – 加法运算符(+)适用于Numeric和Strings。 例如 “a”+ 10将给出“a10”。
以下代码显示了如何在JavaScript中使用算术运算符。
<html> <body> <script type="text/javascript"> <!-- var a = 33; var b = 10; var c = "Test"; var linebreak = "<br />"; document.write("a + b = "); result = a + b; document.write(result); document.write(linebreak); document.write("a - b = "); result = a - b; document.write(result); document.write(linebreak); document.write("a / b = "); result = a / b; document.write(result); document.write(linebreak); document.write("a % b = "); result = a % b; document.write(result); document.write(linebreak); document.write("a + b + c = "); result = a + b + c; document.write(result); document.write(linebreak); a = ++a; document.write("++a = "); result = ++a; document.write(result); document.write(linebreak); b = --b; document.write("--b = "); result = --b; document.write(result); document.write(linebreak); //--> </script> Set the variables to different values and then try... </body> </html>
a + b = 43 a - b = 23 a / b = 3.3 a % b = 3 a + b + c = 43Test ++a = 35 --b = 8 Set the variables to different values and then try...
比较运算符
JavaScript支持以下比较运算符 −
假设变量A保持10,变量B保持20,则 −
序号 | 运算符和描述 |
---|---|
1 |
== (等于) |
2 |
!= (不等于) |
3 |
> (大于) |
4 |
< (小于) |
5 |
>= (大于等于) |
6 |
<= (小于等于) |
以下代码显示了如何在JavaScript中使用比较运算符。
<html> <body> <script type="text/javascript"> <!-- var a = 10; var b = 20; var linebreak = "<br />"; document.write("(a == b) => "); result = (a == b); document.write(result); document.write(linebreak); document.write("(a < b) => "); result = (a < b); document.write(result); document.write(linebreak); document.write("(a > b) => "); result = (a > b); document.write(result); document.write(linebreak); document.write("(a != b) => "); result = (a != b); document.write(result); document.write(linebreak); document.write("(a >= b) => "); result = (a >= b); document.write(result); document.write(linebreak); document.write("(a <= b) => "); result = (a <= b); document.write(result); document.write(linebreak); //--> </script> Set the variables to different values and different operators and then try... </body> </html>
(a == b) => false (a < b) => true (a > b) => false (a != b) => true (a >= b) => false a <= b) => true Set the variables to different values and different operators and then try...
逻辑运算符
JavaScript支持以下逻辑运算符 −
假设变量A保持10,变量B保持20,则 −
序号 | 运算符和描述 |
---|---|
1 | && (Logical AND) 如果两个操作数都不为零,则条件成立。 例如:(A && B)是真的。 |
2 | || (Logical OR) 如果两个操作数中的任何一个非零,则条件变为真。 例如:(A || B)是真的。 |
3 | ! (Logical NOT) 反转其操作数的逻辑状态。 如果条件为真,则Logical NOT运算符将使其为false。 例如: ! (A && B) 是假的。 |
请尝试以下代码以了解如何在JavaScript中实现逻辑运算符。
<html> <body> <script type="text/javascript"> <!-- var a = true; var b = false; var linebreak = "<br />"; document.write("(a && b) => "); result = (a && b); document.write(result); document.write(linebreak); document.write("(a || b) => "); result = (a || b); document.write(result); document.write(linebreak); document.write("!(a && b) => "); result = (!(a && b)); document.write(result); document.write(linebreak); //--> </script> <p>Set the variables to different values and different operators and then try...</p> </body> </html>
(a && b) => false (a || b) => true !(a && b) => true Set the variables to different values and different operators and then try...
位运算符
JavaScript支持以下按位运算符 −
假设变量A保持2而变量B保持3,则 −
序号 | 运算符和描述 |
---|---|
1 | & (Bitwise AND) 它对其整数参数的每个位执行布尔AND运算。 例如:(A&B)是2。 |
2 | | (BitWise OR) 它对其整数参数的每个位执行布尔OR运算。 例如:(A | B)是3。 |
3 | ^ (Bitwise XOR) 它对其整数参数的每个位执行布尔异或运算。 异或表示操作数1为真或操作数2为真,但不是两者。 例如:(A ^ B)是1。 |
4 | ~ (Bitwise Not) 它是一元运算符,通过反转操作数中的所有位来操作。 例如:( ~B)是-4。 |
5 | << (Left Shift) 它将第一个操作数中的所有位向左移动第二个操作数中指定的位数。 新位用零填充。 将一个值左移一个位置相当于将其乘以2,移位两个位置相当于乘以4,依此类推。 例如:(A << 1) 是 4. |
6 | >> (Right Shift) 二进制右移运算符。 左操作数的值向右移动右操作数指定的位数。 例如: (A >> 1) 是 1. |
7 | >>> (Right shift with Zero) 这个运算符就像>>运算符一样,只不过在左边移入的位总是为零。 例如: (A >>> 1) 是 1. |
尝试使用以下代码在JavaScript中实现Bitwise运算符。
<html> <body> <script type="text/javascript"> <!-- var a = 2; // Bit presentation 10 var b = 3; // Bit presentation 11 var linebreak = "<br />"; document.write("(a & b) => "); result = (a & b); document.write(result); document.write(linebreak); document.write("(a | b) => "); result = (a | b); document.write(result); document.write(linebreak); document.write("(a ^ b) => "); result = (a ^ b); document.write(result); document.write(linebreak); document.write("(~b) => "); result = (~b); document.write(result); document.write(linebreak); document.write("(a << b) => "); result = (a << b); document.write(result); document.write(linebreak); document.write("(a >> b) => "); result = (a >> b); document.write(result); document.write(linebreak); //--> </script> <p>Set the variables to different values and different operators and then try...</p> </body> </html>
(a & b) => 2 (a | b) => 3 (a ^ b) => 1 (~b) => -4 (a << b) => 16 (a >> b) => 0 Set the variables to different values and different operators and then try...
赋值运算符
JavaScript支持以下赋值运算符 −
序号 | 运算符和描述 |
---|---|
1 | = (Simple Assignment ) 将值从右侧操作数分配给左侧操作数 例如:C = A + B将A + B的值分配给C |
2 | += (Add and Assignment) 它将右操作数添加到左操作数并将结果赋给左操作数。 例:C + = A等于C = C + A. |
3 | −= (Subtract and Assignment) 它从左操作数中减去右操作数,并将结果赋给左操作数。 例:C – = A相当于C = C – A. |
4 | *= (Multiply and Assignment) 它将右操作数与左操作数相乘,并将结果赋给左操作数。 例:C * = A等于C = C * A. |
5 | /= (Divide and Assignment) 它将左操作数与右操作数分开,并将结果赋给左操作数。 例:C /= A等于C = C/A. |
6 | %= (Modules and Assignment) 它使用两个操作数来获取模数,并将结果赋给左操作数。 例:C%= A等于C = C%A |
注 – 相同的逻辑适用于按位运算符,因此它们将变为<<=, >>=, >>=, &=, |= and ^=。
尝试使用以下代码在JavaScript中实现赋值运算符。
<html> <body> <script type="text/javascript"> <!-- var a = 33; var b = 10; var linebreak = "<br />"; document.write("Value of a => (a = b) => "); result = (a = b); document.write(result); document.write(linebreak); document.write("Value of a => (a += b) => "); result = (a += b); document.write(result); document.write(linebreak); document.write("Value of a => (a -= b) => "); result = (a -= b); document.write(result); document.write(linebreak); document.write("Value of a => (a *= b) => "); result = (a *= b); document.write(result); document.write(linebreak); document.write("Value of a => (a /= b) => "); result = (a /= b); document.write(result); document.write(linebreak); document.write("Value of a => (a %= b) => "); result = (a %= b); document.write(result); document.write(linebreak); //--> </script> <p>Set the variables to different values and different operators and then try...</p> </body> </html>
Value of a => (a = b) => 10 Value of a => (a += b) => 20 Value of a => (a -= b) => 10 Value of a => (a *= b) => 100 Value of a => (a /= b) => 10 Value of a => (a %= b) => 0 Set the variables to different values and different operators and then try...
杂项运算符
我们将在这里讨论两个在JavaScript中非常有用的运算符:条件运算符(?:)和typeof运算符。
条件运算符 (? 🙂
条件运算符首先计算表达式的true或false值,然后根据评估结果执行两个给定语句中的一个。
序号 | 运算符和描述 |
---|---|
1 | ? : (条件) 如果条件为真? 然后是值X:否则为Y值 |
请尝试以下代码以了解条件运算符在JavaScript中的工作方式。
<html> <body> <script type="text/javascript"> <!-- var a = 10; var b = 20; var linebreak = "<br />"; document.write ("((a > b) ? 100 : 200) => "); result = (a > b) ? 100 : 200; document.write(result); document.write(linebreak); document.write ("((a < b) ? 100 : 200) => "); result = (a < b) ? 100 : 200; document.write(result); document.write(linebreak); //--> </script> <p>Set the variables to different values and different operators and then try...</p> </body> </html>
((a > b) ? 100 : 200) => 200 ((a < b) ? 100 : 200) => 100 Set the variables to different values and different operators and then try...
typeof运算符
typeof运算符是一元运算符,位于其单个操作数之前,可以是任何类型。 它的值是一个字符串,表示操作数的数据类型。
如果操作数是数字,字符串或布尔值,则typeof运算符求值为“number”,“string”或“boolean”,并根据求值返回true或false。
以下是typeof运算符的返回值列表。
类型 | 由typeof返回的字符串 |
---|---|
Number | “number” |
String | “string” |
Boolean | “boolean” |
Object | “object” |
Function | “function” |
Undefined | “undefined” |
Null | “object” |
以下代码显示了如何实现typeof运算符。
<html> <body> <script type="text/javascript"> <!-- var a = 10; var b = "String"; var linebreak = "<br />"; result = (typeof b == "string" ? "B is String" : "B is Numeric"); document.write("Result => "); document.write(result); document.write(linebreak); result = (typeof a == "string" ? "A is String" : "A is Numeric"); document.write("Result => "); document.write(result); document.write(linebreak); //--> </script> <p>Set the variables to different values and different operators and then try...</p> </body> </html>
Result => B is String Result => A is Numeric Set the variables to different values and different operators and then try...
条件
在编写程序时,可能存在需要从给定路径集中采用一个程序的情况。 在这种情况下,您需要使用条件语句,以允许您的程序做出正确的决策并执行正确的操作。
JavaScript支持条件语句,用于根据不同的条件执行不同的操作。 这里我们将解释if..else语句。
if-else流程图
以下流程图显示了if-else语句的工作原理。
JavaScript支持以下形式的if..else语句 −
- if 语句
- if…else 语句
- if…else if… 语句
if 语句
if语句是允许JavaScript有条件地做出决策和执行语句的基本控制语句。
语法
基本if语句的语法如下 −
if (expression){ Statement(s) to be executed if expression is true }
这里评估JavaScript表达式。 如果结果值为true,则执行给定的语句。 如果表达式为false,则不会执行任何语句。 大多数情况下,您将在做出决策时使用比较运算符。
请尝试以下示例以了解if语句的工作原理。
<html> <body> <script type="text/javascript"> <!-- var age = 20; if( age > 18 ){ document.write("<b>Qualifies for driving</b>"); } //--> </script> <p>Set the variable to different value and then try...</p> </body> </html>
Qualifies for driving Set the variable to different value and then try...
if…else 语句:
‘if … else’语句是控制语句的下一种形式,它允许JavaScript以更加可控的方式执行语句。
语法
if (expression){ Statement(s) to be executed if expression is true } else{ Statement(s) to be executed if expression is false }
这里评估了JavaScript表达式。 如果结果值为true,则执行“if”块中的给定语句。 如果表达式为false,则执行else块中的给定语句。
例子
请尝试以下代码以了解如何在JavaScript中实现if-else语句。
<html> <body> <script type="text/javascript"> <!-- var age = 15; if( age > 18 ){ document.write("<b>Qualifies for driving</b>"); } else{ document.write("<b>Does not qualify for driving</b>"); } //--> </script> <p>Set the variable to different value and then try...</p> </body> </html>
输出
Does not qualify for driving Set the variable to different value and then try...
if…else if… 语句
if … else if …语句是if … else的高级形式,允许JavaScript在几个条件下做出正确的决定。
语法
if-else-if语句的语法如下 −
if (expression 1){ Statement(s) to be executed if expression 1 is true } else if (expression 2){ Statement(s) to be executed if expression 2 is true } else if (expression 3){ Statement(s) to be executed if expression 3 is true } else{ Statement(s) to be executed if no expression is true }
这段代码没有什么特别之处。 它只是一系列if语句,其中每个if都是前一个语句的else子句的一部分。 语句是根据真实条件执行的,如果没有条件为真,则执行else块。
例子
请尝试以下代码以了解如何在JavaScript中实现if-else-if语句。
<html> <body> <script type="text/javascript"> <!-- var book = "maths"; if( book == "history" ){ document.write("<b>History Book</b>"); } else if( book == "maths" ){ document.write("<b>Maths Book</b>"); } else if( book == "economics" ){ document.write("<b>Economics Book</b>"); } else{ document.write("<b>Unknown Book</b>"); } //--> </script> <p>Set the variable to different value and then try...</p> </body> </html>
输出
Maths Book Set the variable to different value and then try...
分支
您可以使用多个if … else … if语句(如上一章所述)来执行多路分支。 但是,这并不总是最佳解决方案,尤其是当所有分支都依赖于单个变量的值时。
从JavaScript 1.2开始,您可以使用switch语句来处理这种情况,并且它比重复if … else if语句更有效。
流程图
以下流程图说明了switch-case语句的工作原理。
语法
switch语句的目标是给出一个表达式来评估,并根据表达式的值执行几个不同的语句。 解释器根据表达式的值检查每个案例,直到找到匹配项。 如果没有匹配,将使用默认条件。
switch (expression) { case condition 1: statement(s) break; case condition 2: statement(s) break; ... case condition n: statement(s) break; default: statement(s) }
break语句表示特定案例的结束。 如果省略它们,则解释器将在以下每种情况下继续执行每个语句。
我们将在循环控制章节中解释break语句。
例子
请尝试以下示例来实现switch-case语句。
<html> <body> <script type="text/javascript"> <!-- var grade='A'; document.write("Entering switch block<br />"); switch (grade) { case 'A': document.write("Good job<br />"); break; case 'B': document.write("Pretty good<br />"); break; case 'C': document.write("Passed<br />"); break; case 'D': document.write("Not so good<br />"); break; case 'F': document.write("Failed<br />"); break; default: document.write("Unknown grade<br />") } document.write("Exiting switch block"); //--> </script> <p>Set the variable to different value and then try...</p> </body> </html>
输出
Entering switch block Good job Exiting switch block Set the variable to different value and then try...
Break语句在switch-case语句中起主要作用。 尝试使用switch-case语句的以下代码,不带任何break语句。
<html> <body> <script type="text/javascript"> <!-- var grade='A'; document.write("Entering switch block<br />"); switch (grade) { case 'A': document.write("Good job<br />"); case 'B': document.write("Pretty good<br />"); case 'C': document.write("Passed<br />"); case 'D': document.write("Not so good<br />"); case 'F': document.write("Failed<br />"); default: document.write("Unknown grade<br />") } document.write("Exiting switch block"); //--> </script> <p>Set the variable to different value and then try...</p> </body> </html>
输出
Entering switch block Good job Pretty good Passed Not so good Failed Unknown grade Exiting switch block Set the variable to different value and then try...
While循环
编写程序时,您可能会遇到需要反复执行操作的情况。 在这种情况下,您需要编写循环语句以减少行数。
JavaScript支持所有必要的循环,以减轻编程压力。
while循环
JavaScript中最基本的循环是while循环,将在本章中讨论。 while循环的目的是只要表达式为真,就重复执行语句或代码块。 表达式变为false后,循环终止。
流程图
while循环的流程图如下 −
语法
JavaScript中while循环的语法如下 −
while (expression){ Statement(s) to be executed if expression is true }
例子
请尝试以下示例来实现while循环。
<html> <body> <script type="text/javascript"> <!-- var count = 0; document.write("Starting Loop "); while (count < 10){ document.write("Current Count : " + count + "<br />"); count++; } document.write("Loop stopped!"); //--> </script> <p>Set the variable to different value and then try...</p> </body> </html>
输出
Starting Loop Current Count : 0 Current Count : 1 Current Count : 2 Current Count : 3 Current Count : 4 Current Count : 5 Current Count : 6 Current Count : 7 Current Count : 8 Current Count : 9 Loop stopped! Set the variable to different value and then try...
do…while循环
do … while循环类似于while循环,除了条件检查发生在循环结束时。 这意味着循环将始终至少执行一次,即使条件为假。
流程图
The flow chart of a do-while loop would be as follows −
语法
do-while循环的流程图如下 −
do{ Statement(s) to be executed; } while (expression);
注意 – 不要错过do … while循环结束时使用的分号。
例子
请尝试以下示例,以了解如何在JavaScript中实现do-while循环。
<html> <body> <script type="text/javascript"> <!-- var count = 0; document.write("Starting Loop" + "<br />"); do{ document.write("Current Count : " + count + "<br />"); count++; } while (count < 5); document.write ("Loop stopped!"); //--> </script> <p>Set the variable to different value and then try...</p> </body> </html>
输出
Starting Loop Current Count : 0 Current Count : 1 Current Count : 2 Current Count : 3 Current Count : 4 Loop Stopped! Set the variable to different value and then try...
For循环
‘for’循环是最紧凑的循环形式。 它包括以下三个重要部分 −
- 循环初始化,我们将计数器初始化为起始值。 初始化语句在循环开始之前执行。
- 测试语句将测试给定条件是否为真。 如果条件为真,则执行循环内给出的代码,否则控件将退出循环。
- 迭代语句,您可以在其中增加或减少计数器。
您可以将所有三个部分放在一行中以分号分隔。
流程图
JavaScript中for循环的流程图如下 −
语法
for循环的语法是JavaScript如下 −
for (initialization; test condition; iteration statement){ Statement(s) to be executed if test condition is true }
例子
请尝试以下示例,了解for循环在JavaScript中的工作原理。
<html> <body> <script type="text/javascript"> <!-- var count; document.write("Starting Loop" + "<br />"); for(count = 0; count < 10; count++){ document.write("Current Count : " + count ); document.write("<br />"); } document.write("Loop stopped!"); //--> </script> <p>Set the variable to different value and then try...</p> </body> </html>
输出
Starting Loop Current Count : 0 Current Count : 1 Current Count : 2 Current Count : 3 Current Count : 4 Current Count : 5 Current Count : 6 Current Count : 7 Current Count : 8 Current Count : 9 Loop stopped! Set the variable to different value and then try...
For…in循环
for … in循环用于循环对象的属性。 由于我们尚未讨论对象,您可能对此循环感到不舒服。 但是一旦你理解了对象在JavaScript中的行为方式,你会发现这个循环非常有用。
语法
for (variablename in object){ statement or block to execute }
在每次迭代中,对象的一个属性被赋值给variablename,并且此循环继续,直到对象的所有属性都用完为止。
例子
尝试以下示例来实现’for-in’循环。 它打印Web浏览器的Navigator对象。
<html> <body> <script type="text/javascript"> <!-- var aProperty; document.write("Navigator Object Properties<br /> "); for (aProperty in navigator) { document.write(aProperty); document.write("<br />"); } document.write ("Exiting from the loop!"); //--> </script> <p>Set the variable to different object and then try...</p> </body> </html>
输出
Navigator Object Properties serviceWorker webkitPersistentStorage webkitTemporaryStorage geolocation doNotTrack onLine languages language userAgent product platform appVersion appName appCodeName hardwareConcurrency maxTouchPoints vendorSub vendor productSub cookieEnabled mimeTypes plugins javaEnabled getStorageUpdates getGamepads webkitGetUserMedia vibrate getBattery sendBeacon registerProtocolHandler unregisterProtocolHandler Exiting from the loop! Set the variable to different object and then try...
循环控制
JavaScript提供了完全控制来处理循环和switch语句。 可能存在这样一种情况,即您需要在没有到达底部的情况下退出循环。 当您想跳过代码块的一部分并开始下一次循环迭代时,可能还会出现这种情况。
为了处理所有这些情况,JavaScript提供了break和continue语句。 这些语句用于立即从任何循环中出来或分别开始任何循环的下一次迭代。
break语句
使用switch语句简要介绍的break语句用于提前退出循环,打破封闭的花括号。
流程图
break语句的流程图如下所示 −
例子
以下示例说明了使用带有while循环的break语句。 注意一旦x到达5,循环就会提前爆发,并且到达右大括号的document.write(..)语句 −
<html> <body> <script type="text/javascript"> <!-- var x = 1; document.write("Entering the loop<br /> "); while (x < 20) { if (x == 5){ break; // breaks out of loop completely } x = x + 1; document.write( x + "<br />"); } document.write("Exiting the loop!<br /> "); //--> </script> <p>Set the variable to different value and then try...</p> </body> </html>
输出
Entering the loop 2 3 4 5 Exiting the loop! Set the variable to different value and then try...
我们已经在switch语句中看到了break语句的用法。
continue语句
continue语句告诉解释器立即启动循环的下一次迭代并跳过剩余的代码块。 当遇到continue语句时,程序流立即移动到循环检查表达式,如果条件保持为真,则它开始下一次迭代,否则控件退出循环。
例子
此示例说明了使用带有while循环的continue语句。 注意当变量x中保存的索引达到5时,如何使用continue语句跳过打印 – −
<html> <body> <script type="text/javascript"> <!-- var x = 1; document.write("Entering the loop<br /> "); while (x < 10) { x = x + 1; if (x == 5){ continue; // skip rest of the loop body } document.write( x + "<br />"); } document.write("Exiting the loop!<br /> "); //--> </script> <p>Set the variable to different value and then try...</p> </body> </html>
输出
Entering the loop 2 3 4 6 7 8 9 10 Exiting the loop!
使用标签来控制流量
从JavaScript 1.2开始,标签可以与break一起使用并继续更精确地控制流程。 标签只是一个标识符,后跟冒号(:),应用于语句或代码块。 我们将看到两个不同的示例,以了解如何使用break和continue标签。
注 – “continue”或“break”语句与其标签名称之间不允许换行符。 此外,标签名称和关联循环之间不应该有任何其他语句。
尝试以下两个示例以更好地理解标签。
例子 1
以下示例显示如何使用break语句实现Label。
<html> <body> <script type="text/javascript"> <!-- document.write("Entering the loop!<br /> "); outerloop: // This is the label name for (var i = 0; i < 5; i++) { document.write("Outerloop: " + i + "<br />"); innerloop: for (var j = 0; j < 5; j++) { if (j > 3 ) break ; // Quit the innermost loop if (i == 2) break innerloop; // Do the same thing if (i == 4) break outerloop; // Quit the outer loop document.write("Innerloop: " + j + " <br />"); } } document.write("Exiting the loop!<br /> "); //--> </script> </body> </html>
输出
Entering the loop! Outerloop: 0 Innerloop: 0 Innerloop: 1 Innerloop: 2 Innerloop: 3 Outerloop: 1 Innerloop: 0 Innerloop: 1 Innerloop: 2 Innerloop: 3 Outerloop: 2 Outerloop: 3 Innerloop: 0 Innerloop: 1 Innerloop: 2 Innerloop: 3 Outerloop: 4 Exiting the loop!
例子 2
<html> <body> <script type="text/javascript"> <!-- document.write("Entering the loop!<br /> "); outerloop: // This is the label name for (var i = 0; i < 3; i++) { document.write("Outerloop: " + i + "<br />"); for (var j = 0; j < 5; j++) { if (j == 3){ continue outerloop; } document.write("Innerloop: " + j + "<br />"); } } document.write("Exiting the loop!<br /> "); //--> </script> </body> </html>
输出
Entering the loop! Outerloop: 0 Innerloop: 0 Innerloop: 1 Innerloop: 2 Outerloop: 1 Innerloop: 0 Innerloop: 1 Innerloop: 2 Outerloop: 2 Innerloop: 0 Innerloop: 1 Innerloop: 2 Exiting the loop!
函数
函数是一组可重用的代码,可以在程序中的任何位置调用。 这消除了一次又一次地编写相同代码的需要。 它可以帮助程序员编写模块化代码。 函数允许程序员将大程序划分为许多小而易于管理的函数。
与任何其他高级编程语言一样,JavaScript也支持使用函数编写模块化代码所需的所有功能。 您必须在前面的章节中看到过alert()和write()等函数。 我们一次又一次地使用这些函数,但它们只用核心JavaScript编写过一次。
JavaScript允许我们编写自己的函数。 本节介绍如何使用JavaScript编写自己的函数。
函数定义
在我们使用函数之前,我们需要定义它。 在JavaScript中定义函数的最常用方法是使用function关键字,后跟唯一的函数名称,参数列表(可能为空),以及由大括号括起的语句块。
语法
这里显示了基本语法。
<script type="text/javascript"> <!-- function functionname(parameter-list) { statements } //--> </script>
例子
请尝试以下示例。 它定义了一个名为sayHello的函数,它不带参数 −
<script type="text/javascript"> <!-- function sayHello() { alert("Hello there"); } //--> </script>
调用函数
要在稍后的脚本中调用函数,您只需要编写该函数的名称,如以下代码所示。
<html> <head> <script type="text/javascript"> function sayHello() { document.write ("Hello there!"); } </script> </head> <body> <p>Click the following button to call the function</p> <form> <input type="button" onclick="sayHello()" value="Say Hello"> </form> <p>Use different text in write method and then try...</p> </body> </html>
函数参数
到目前为止,我们已经看到没有参数的函数。 但是在调用函数时有一个传递不同参数的工具。 可以在函数内捕获这些传递的参数,并且可以对这些参数进行任何操作。 函数可以采用逗号分隔的多个参数。
例子
请尝试以下示例。 我们在这里修改了sayHello函数。 现在需要两个参数。
<html> <head> <script type="text/javascript"> function sayHello(name, age) { document.write (name + " is " + age + " years old."); } </script> </head> <body> <p>Click the following button to call the function</p> <form> <input type="button" onclick="sayHello('Zara', 7)" value="Say Hello"> </form> <p>Use different parameters inside the function and then try...</p> </body> </html>
return语句
JavaScript函数可以有一个可选的return语句。 如果要从函数返回值,则需要这样做。 该语句应该是函数中的最后一个语句。
例如,您可以在函数中传递两个数字,然后您可以期望该函数在您的调用程序中返回它们的乘法。
例子
请尝试以下示例。 它定义了一个函数,它接受两个参数并在调用程序中返回结果之前将它们连接起来。
<html> <head> <script type="text/javascript"> function concatenate(first, last) { var full; full = first + last; return full; } function secondFunction() { var result; result = concatenate('Zara', 'Ali'); document.write (result ); } </script> </head> <body> <p>Click the following button to call the function</p> <form> <input type="button" onclick="secondFunction()" value="Call Function"> </form> <p>Use different parameters inside the function and then try...</p> </body> </html>
有很多关于JavaScript函数的知识,但是我们已经介绍了本教程中最重要的概念。
- JavaScript嵌套函数
- JavaScript构造函数
- JavaScript函数显式声明
JavaScript嵌套函数
在JavaScript 1.2之前,函数定义仅允许在顶级全局代码中使用,但JavaScript 1.2允许函数定义也嵌套在其他函数中。 仍存在一个限制,即函数定义可能不会出现在循环或条件中。 这些对函数定义的限制仅适用于函数声明的函数声明。
正如我们将在下一章稍后讨论的那样,函数文字(JavaScript 1.2中引入的另一个特性)可能出现在任何JavaScript表达式中,这意味着它们可以出现在if和其他语句中。
例子
请尝试以下示例以了解如何实现嵌套函数。
<html> <head> <script type="text/javascript"> <!-- function hypotenuse(a, b) { function square(x) { return x*x; } return Math.sqrt(square(a) + square(b)); } function secondFunction(){ var result; result = hypotenuse(1,2); document.write ( result ); } //--> </script> </head> <body> <p>Click the following button to call the function</p> <form> <input type="button" onclick="secondFunction()" value="Call Function"> </form> <p>Use different parameters inside the function and then try...</p> </body> </html>
JavaScript构造函数
函数语句不是定义新函数的唯一方法; 您可以使用Function()构造函数和new运算符动态定义函数。
注 – 构造函数是面向对象编程的术语。 你可能第一次感到不舒服,这没关系。
语法
以下是使用Function()构造函数和new运算符创建函数的语法。
<script type="text/javascript"> <!-- var variablename = new Function(Arg1, Arg2..., "Function Body"); //--> </script>
Function()构造函数需要任意数量的字符串参数。 最后一个参数是函数体 – 它可以包含任意JavaScript语句,用分号相互分隔。
请注意,Function()构造函数未传递任何指定其创建的函数名称的参数。 使用Function()构造函数创建的未命名函数称为匿名函数。
请尝试以下示例。
<html> <head> <script type="text/javascript"> <!-- var func = new Function("x", "y", "return x*y;"); function secondFunction(){ var result; result = func(10,20); document.write ( result ); } //--> </script> </head> <body> <p>Click the following button to call the function</p> <form> <input type="button" onclick="secondFunction()" value="Call Function"> </form> <p>Use different parameters inside the function and then try...</p> </body> </html>
JavaScript函数显式声明
JavaScript 1.2引入了函数显式声明的概念,这是另一种定义函数的新方法。 函数文字是定义未命名函数的表达式。
语法
函数显式声明的语法很像函数语句,除了它用作表达式而不是语句,不需要函数名。
<script type="text/javascript"> <!-- var variablename = function(Argument List){ Function Body }; //--> </script>
从语法上讲,您可以在创建函数显式声明时指定函数名称,如下所示。
<script type="text/javascript"> <!-- var variablename = function FunctionName(Argument List){ Function Body }; //--> </script>
但这个名字没有任何意义,所以不值得。
请尝试以下示例。 它显示了函数显式声明的用法。
<html> <head> <script type="text/javascript"> <!-- var func = function(x,y){ return x*y }; function secondFunction(){ var result; result = func(10,20); document.write ( result ); } //--> </script> </head> <body> <p>Click the following button to call the function</p> <form> <input type="button" onclick="secondFunction()" value="Call Function"> </form> <p>Use different parameters inside the function and then try...</p> </body> </html>
事件
什么是事件?
JavaScript与HTML的交互是通过用户或浏览器操作页面时发生的事件来处理的。
页面加载时,称为事件。 当用户单击按钮时,该单击也是一个事件。 其他示例包括按任意键,关闭窗口,调整窗口大小等事件。
开发人员可以使用这些事件来执行JavaScript编码响应,这会导致按钮关闭窗口,向用户显示消息,要验证的数据以及几乎可以想象的任何其他类型的响应。
事件是文档对象模型(DOM)级别3的一部分,每个HTML元素都包含一组可以触发JavaScript代码的事件。
请仔细阅读这个小教程,以便更好地理解HTML事件参考。 在这里,我们将看到几个例子来理解Event和JavaScript之间的关系 −
onclick事件类型
这是用户单击鼠标左键时最常用的事件类型。 您可以针对此事件类型进行验证,警告等。
例子
请尝试以下示例。
<html> <head> <script type="text/javascript"> <!-- function sayHello() { alert("Hello World") } //--> </script> </head> <body> <p>Click the following button and see result</p> <form> <input type="button" onclick="sayHello()" value="Say Hello" /> </form> </body> </html>
onsubmit事件类型
onsubmit是您尝试提交表单时发生的事件。 您可以针对此事件类型进行表单验证。
例子
以下示例显示如何使用onsubmit。 这里我们在将表单数据提交给Web服务器之前调用validate()函数。 如果validate()函数返回true,则表单将被提交,否则将不提交数据。
请尝试以下示例
<html> <head> <script type="text/javascript"> <!-- function validation() { all validation goes here ......... return either true or false } //--> </script> </head> <body> <form method="POST" action="t.cgi" onsubmit="return validate()"> ....... <input type="submit" value="Submit" /> </form> </body> </html>
onmouseover和onmouseout
这两种事件类型将帮助您创建图像甚至文本的精美效果。 将鼠标悬停在任何元素上时触发onmouseover事件,当您将鼠标从该元素移出时触发onmouseout事件。 请尝试以下示例。
<html> <head> <script type="text/javascript"> <!-- function over() { document.write ("Mouse Over"); } function out() { document.write ("Mouse Out"); } //--> </script> </head> <body> <p>Bring your mouse inside the division to see the result:</p> <div onmouseover="over()" onmouseout="out()"> <h2> This is inside the division </h2> </div> </body> </html>
HTML 5 标准事件
此处列出了标准HTML 5事件供您参考。 这里脚本表示要对该事件执行的Javascript函数。
属性 | 描述 |
---|---|
Offline | 文档脱机时触发 |
Onabort | 触发中止事件 |
onafterprint | 打印文档后触发 |
onbeforeonload | 文档加载前触发 |
onbeforeprint | 打印文档前触发 |
onblur | 窗口失去焦点时触发 |
oncanplay | 媒体可以开始播放时触发,但可能必须停止缓冲 |
oncanplaythrough | 当媒体可以播放到最后时触发,而不停止缓冲 |
onchange | 元素更改时触发 |
onclick | 单击鼠标时触发 |
oncontextmenu | 触发上下文菜单时触发 |
ondblclick | 双击鼠标触发 |
ondrag | 拖动元素时触发 |
ondragend | 拖动操作结束时触发 |
ondragenter | 将元素拖动到有效放置目标时触发 |
ondragleave | 在有效放置目标上拖动元素时触发 |
ondragover | 在拖动操作开始时触发 |
ondragstart | 在拖动操作开始时触发 |
ondrop | 删除拖动元素时触发 |
ondurationchange | 更改介质长度时触发 |
onemptied | 媒体资源元素突然变空时触发。 |
onended | 媒体到达终点时触发 |
onerror | 发生错误时触发 |
onfocus | 窗口获得焦点时触发 |
onformchange | 表单更改时触发 |
onforminput | 表单获取用户输入时触发 |
onhaschange | 文档更改时触发 |
oninput | 元素获取用户输入时触发 |
oninvalid | 元素无效时触发 |
onkeydown | 按下某个键时触发 |
onkeypress | 按下并释放按键时触发 |
onkeyup | 释放按键时触发 |
onload | 文档加载时触发 |
onloadeddata | 加载媒体数据时触发 |
onloadedmetadata | 加载媒体元素的持续时间和其他媒体数据时触发 |
onloadstart | 浏览器开始加载媒体数据时触发 |
onmessage | 触发消息时触发 |
onmousedown | 按下鼠标按钮时触发 |
onmousemove | 鼠标指针移动时触发 |
onmouseout | 鼠标指针移出元素时触发 |
onmouseover | 鼠标指针在元素上移动时触发 |
onmouseup | 释放鼠标按钮时触发 |
onmousewheel | 旋转鼠标滚轮时触发 |
onoffline | 文档脱机时触发 |
onoine | 文档联机时触发 |
ononline | 文档联机时触发 |
onpagehide | 隐藏窗口时触发 |
onpageshow | 窗口变为可见时触发 |
onpause | 媒体数据暂停时触发 |
onplay | 媒体数据开始播放时触发 |
onplaying | 媒体数据开始播放时触发 |
onpopstate | 窗口历史记录更改时触发 |
onprogress | 浏览器获取媒体数据时触发 |
onratechange | 媒体数据的播放速率发生变化时触发 |
onreadystatechange | 准备状态改变时触发 |
onredo | 文档执行重做时触发 |
onresize | 调整窗口大小时触发 |
onscroll | 滚动元素的滚动条时触发 |
onseeked | 当媒体元素的搜索属性不再为真时触发,并且搜索已经结束 |
onseeking | 当媒体元素的搜索属性为真时触发,并且搜索已经开始 |
onselect | 选择元素时触发 |
onstalled | 在获取媒体数据时出现错误时触发 |
onstorage | 文档加载时触发 |
onsubmit | 提交表单时触发 |
onsuspend | 浏览器获取媒体数据时触发,但在获取整个媒体文件之前停止 |
ontimeupdate | 媒体更改其播放位置时触发 |
onundo | 文档执行撤消时触发 |
onunload | 用户离开文档时触发 |
onvolumechange | 媒体更改音量时触发,当音量设置为“静音”时触发 |
onwaiting | 媒体停止播放时触发,但预计会恢复 |
Cookies
什么是Cookies ?
Web浏览器和服务器使用HTTP协议进行通信,HTTP是无状态协议。 但对于商业网站,需要在不同页面之间维护会话信息。 例如,一个用户注册在完成许多页面后结束。 但是如何在所有网页上维护用户的会话信息。
在许多情况下,使用Cookie是记住和跟踪偏好,购买,佣金以及更好的访问者体验或网站统计所需的其他信息的最有效方法。
怎么工作的 ?
您的服务器以cookie的形式向访问者的浏览器发送一些数据。 浏览器可以接受cookie。 如果是,则将其作为纯文本记录存储在访问者的硬盘上。 现在,当访问者到达您站点上的另一个页面时,浏览器会将相同的cookie发送到服务器以进行检索。 检索后,您的服务器会知道/记住之前存储的内容。
Cookie是5个可变长度字段的纯文本数据记录 −
- Expires − Cookie过期的日期。 如果这是空白,则访问者退出浏览器时cookie将过期。
- Domain − 您网站的域名。
- Path − 设置cookie的目录或网页的路径。 如果要从任何目录或页面检索cookie,这可能为空。
- Secure − 如果此字段包含单词“secure”,则只能使用安全服务器检索cookie。 如果此字段为空,则不存在此类限制。
- Name=Value − Cookie以键值对的形式设置和检索
Cookie最初是为CGI编程而设计的。 cookie中包含的数据在Web浏览器和Web服务器之间自动传输,因此服务器上的CGI脚本可以读取和写入存储在客户端上的cookie值。
JavaScript还可以使用Document对象的cookie属性来操作cookie。 JavaScript可以读取,创建,修改和删除适用于当前网页的cookie。
存储Cookies
创建cookie的最简单方法是为document.cookie对象分配一个字符串值,如下所示。
document.cookie = "key1=value1;key2=value2;expires=date";
这里expires属性是可选的。 如果您为此属性提供有效的日期或时间,则Cookie将在给定的日期或时间到期,此后,cookie的值将无法访问。
注 – Cookie值可能不包括分号,逗号或空格。 因此,您可能希望使用JavaScript escape()函数对值进行编码,然后将其存储在cookie中。 如果这样做,您还必须在读取cookie值时使用相应的unescape()函数。
例子
请尝试以下方法。 它在输入cookie中设置客户名称。
<html> <head> <script type = "text/javascript"> <!-- function WriteCookie() { if( document.myform.customer.value == "" ){ alert("Enter some value!"); return; } cookievalue= escape(document.myform.customer.value) + ";"; document.cookie="name=" + cookievalue; document.write ("Setting Cookies : " + "name=" + cookievalue ); } //--> </script> </head> <body> <form name="myform" action=""> Enter name: <input type="text" name="customer"/> <input type="button" value="Set Cookie" onclick="WriteCookie();"/> </form> </body> </html>
现在你的机器有一个名为name的cookie。 您可以使用以逗号分隔的多个key = value对设置多个cookie。
读取Cookies
读取cookie就像写一个cookie一样简单,因为document.cookie对象的值是cookie。 因此,只要您想访问cookie,就可以使用此字符串。 document.cookie字符串将保留由分号分隔的名称=值对的列表,其中name是cookie的名称,value是其字符串值。
您可以使用字符串的split()函数将字符串分解为键和值,如下所示 −
例子
请尝试以下示例以获取所有Cookie。
<html> <head> <script type="text/javascript"> <!-- function ReadCookie() { var allcookies = document.cookie; document.write ("All Cookies : " + allcookies ); // Get all the cookies pairs in an array cookiearray = allcookies.split(';'); // Now take key value pair out of this array for(var i=0; i<cookiearray.length; i++){ name = cookiearray[i].split('=')[0]; value = cookiearray[i].split('=')[1]; document.write ("Key is : " + name + " and Value is : " + value); } } //--> </script> </head> <body> <form name="myform" action=""> <p> click the following button and see the result:</p> <input type="button" value="Get Cookie" onclick="ReadCookie()"/> </form> </body> </html>
注 – 这里length是Array类的一种方法,它返回一个数组的长度。 我们将在另一章中讨论数组。 到那时,请尝试消化它。
注 – 您的计算机上可能已设置了一些其他Cookie。 上面的代码将显示您计算机上设置的所有Cookie。
设置Cookie到期日
您可以通过设置过期日期并在cookie中保存到期日期来延长cookie的生命周期,使其超出当前浏览器会话。 这可以通过将’expires’属性设置为日期和时间来完成。
例子
请尝试以下示例。 它说明了如何将cookie的到期日期延长1个月。
<html> <head> <script type="text/javascript"> <!-- function WriteCookie() { var now = new Date(); now.setMonth( now.getMonth() + 1 ); cookievalue = escape(document.myform.customer.value) + ";" document.cookie="name=" + cookievalue; document.cookie = "expires=" + now.toUTCString() + ";" document.write ("Setting Cookies : " + "name=" + cookievalue ); } //--> </script> </head> <body> <form name="myform" action=""> Enter name: <input type="text" name="customer"/> <input type="button" value="Set Cookie" onclick="WriteCookie()"/> </form> </body> </html>
删除Cookie
有时您会想要删除cookie,以便随后尝试读取cookie不会返回任何内容。 要执行此操作,您只需将到期日期设置为过去的时间。
例子
请尝试以下示例。 它说明了如何通过将其到期日期设置为当前日期之后一个月来删除cookie。
<html> <head> <script type="text/javascript"> <!-- function WriteCookie() { var now = new Date(); now.setMonth( now.getMonth() - 1 ); cookievalue = escape(document.myform.customer.value) + ";" document.cookie="name=" + cookievalue; document.cookie = "expires=" + now.toUTCString() + ";" document.write("Setting Cookies : " + "name=" + cookievalue ); } //--> </script> </head> <body> <form name="myform" action=""> Enter name: <input type="text" name="customer"/> <input type="button" value="Set Cookie" onclick="WriteCookie()"/> </form> </body> </html>
重定向
什么是页面重定向?
您可能遇到过这样的情况:您单击了一个URL以到达页面X,但在内部您被定向到另一个页面Y.它是由于页面重定向而发生的。 这个概念与JavaScript页面刷新不同
您可能有多种原因要从原始页面重定向用户。 我们列出了一些原因 −
- 您不喜欢您的域名,而您正在转向新域名。 在这种情况下,您可能希望将所有访问者定向到新网站。 在这里,您可以维护旧域,但只需将页面重定向放在一个页面中,以便所有旧域访问者都可以访问新域。
- 您已根据浏览器版本或其名称构建了各种页面,或者可能基于不同的国家/地区,而不是使用服务器端页面重定向,您可以使用客户端页面重定向将用户置于相应的页面上。
- 搜索引擎可能已经为您的网页编制了索引。 但是在转移到另一个域时,您不希望通过搜索引擎丢失访问者。 因此,您可以使用客户端页面重定向。 但请记住,不应该欺骗搜索引擎,它可能导致您的网站被禁止。
页面重定向如何工作?
页面重定向的实现如下。
例子 1
在客户端使用JavaScript进行页面重定向非常简单。 要将您的网站访问者重定向到新页面,您只需在头部添加一行,如下所示。
<html> <head> <script type="text/javascript"> <!-- function Redirect() { window.location="http://www.tutorialspoint.com"; } //--> </script> </head> <body> <p>Click the following button, you will be redirected to home page.</p> <form> <input type="button" value="Redirect Me" onclick="Redirect();" /> </form> </body> </html>
例子 2
在将网站访问者重定向到新网页之前,您可以向网站访问者显示相应的消息。 加载新页面需要一点时间延迟。 以下示例显示了如何实现相同的功能。 这里的setTimeout()是一个内置的JavaScript函数,可以在给定的时间间隔后用于执行另一个函数。
<html> <head> <script type="text/javascript"> <!-- function Redirect() { window.location="http://www.tutorialspoint.com"; } document.write("You will be redirected to main page in 10 sec."); setTimeout('Redirect()', 10000); //--> </script> </head> <body> </body> </html>
例子 3
以下示例说明如何根据浏览器将网站访问者重定向到其他网页。
<html> <head> <script type="text/javascript"> <!-- var browsername=navigator.appName; if( browsername == "Netscape" ) { window.location="http://www.location.com/ns.htm"; } else if ( browsername =="Microsoft Internet Explorer") { window.location="http://www.location.com/ie.htm"; } else { window.location="http://www.location.com/other.htm"; } //--> </script> </head> <body> </body> </html>
对话框
JavaScript支持三种重要类型的对话框。 这些对话框可用于发出警报,或者对任何输入进行确认或从用户那里获得一种输入。 在这里,我们将逐一讨论每个对话框。
警报对话框
警报对话框主要用于向用户发出警告消息。 例如,如果一个输入字段需要输入一些文本但用户不提供任何输入,那么作为验证的一部分,您可以使用警告框来发出警告消息。
尽管如此,警报框仍可用于更友好的消息。 警报框只提供一个“确定”按钮来选择并继续。
例子
<html> <head> <script type="text/javascript"> <!-- function Warn() { alert ("This is a warning message!"); document.write ("This is a warning message!"); } //--> </script> </head> <body> <p>Click the following button to see the result: </p> <form> <input type="button" value="Click Me" onclick="Warn();" /> </form> </body> </html>
确认对话框
确认对话框主要用于征得用户对任何选项的同意。 它显示一个带有两个按钮的对话框:取消。
如果用户单击“确定”按钮,则窗口方法confirm()将返回true。 如果用户单击“取消”按钮,则confirm()返回false。 您可以使用如下确认对话框。
例子
<html> <head> <script type="text/javascript"> <!-- function getConfirmation(){ var retVal = confirm("Do you want to continue ?"); if( retVal == true ){ document.write ("User wants to continue!"); return true; } else{ document.write ("User does not want to continue!"); return false; } } //--> </script> </head> <body> <p>Click the following button to see the result: </p> <form> <input type="button" value="Click Me" onclick="getConfirmation();" /> </form> </body> </html>
提示对话框
当您想要弹出文本框以获取用户输入时,提示对话框非常有用。 因此,它使您能够与用户进行交互。 用户需要填写该字段,然后单击“确定”。
此对话框使用名为prompt()的方法显示,该方法采用两个参数:(i)要在文本框中显示的标签和(ii)要在文本框中显示的默认字符串。
此对话框有两个按钮:确定和取消。 如果用户单击“确定”按钮,则窗口方法提示符()将从文本框中返回输入的值。 如果用户单击“取消”按钮,则窗口方法prompt()将返回null。
例子
以下示例显示如何使用提示对话框 −
<html> <head> <script type="text/javascript"> <!-- function getValue(){ var retVal = prompt("Enter your name : ", "your name here"); document.write("You have entered : " + retVal); } //--> </script> </head> <body> <p>Click the following button to see the result: </p> <form> <input type="button" value="Click Me" onclick="getValue();" /> </form> </body> </html>
Void关键词
void是JavaScript中的一个重要关键字,可以用作在单个操作数之前出现的一元运算符,该操作数可以是任何类型。 此运算符指定要计算的表达式而不返回值。
语法
void的语法可以是以下两种语法之一 −
<head> <script type="text/javascript"> <!-- void func() javascript:void func() or: void(func()) javascript:void(func()) //--> </script> </head>
例子 1
此运算符的最常见用法是在客户端javascript:URL中,它允许您在没有浏览器显示已计算表达式的值的情况下评估表达式的副作用。
这里表达式alert(’Warning !!!’)被评估,但它没有加载回当前文档 −
<html> <head> <script type="text/javascript"> <!-- //--> </script> </head> <body> <p>Click the following, This won't react at all...</p> <a href="javascript:void(alert('Warning!!!'))">Click me!</a> </body> </html>
例子 2
看一下下面的例子。 以下链接不起作用,因为表达式“0”在JavaScript中无效。 这里表达式“0”被计算,但它没有加载回当前文档。
<html> <head> <script type="text/javascript"> <!-- //--> </script> </head> <body> <p>Click the following, This won't react at all...</p> <a href="javascript:void(0)">Click me!</a> </body> </html>
例子 3
void的另一个用途是故意生成未定义的值,如下所示。
<html> <head> <script type="text/javascript"> <!-- function getValue(){ var a,b,c; a = void ( b = 5, c = 7 ); document.write('a = ' + a + ' b = ' + b +' c = ' + c ); } //--> </script> </head> <body> <p>Click the following to see the result:</p> <form> <input type="button" value="Click Me" onclick="getValue();" /> </form> </body> </html>
页面打印
很多时候,您希望在网页上放置一个按钮,通过实际的打印机打印该网页的内容。 JavaScript帮助您使用window对象的print函数实现此功能。
JavaScript打印函数window.print()在执行时打印当前网页。 您可以使用onclick事件直接调用此函数,如以下示例所示。
例子
请尝试以下示例。
<html> <head> <script type="text/javascript"> <!-- //--> </script> </head> <body> <form> <input type="button" value="Print" onclick="window.print()" /> </form> </body> </html>
虽然它用于获取打印输出,但它不是推荐的方式。 打印机友好页面实际上只是一个包含文本,没有图像,图形或广告的页面。
您可以通过以下方式使打印页面 −
- 复制页面并省略不需要的文本和图形,然后从原始页面链接到该打印页面。
- 如果您不想保留页面的额外副本,那么您可以使用适当的注释标记您的可打印文本,例如<!– PRINT STARTS HERE –>….. <!– 打印结束 –> 然后您可以在后台使用PERL或任何其他脚本来清除可打印文本并显示最终打印。 我们Tutorialspoint使用此方法为我们的网站访问者提供打印工具。
如何打印页面
如果在网页上找不到上述功能,则可以使用浏览器的标准工具栏打印网页。 请按照以下链接进行操作。
File → Print → Click OK button.