注:我对原文进行了编辑,对一些词汇标注颜色,方便阅读。本来准备翻译,但是觉得文章简单易懂,而且原文写得很好,所以就不献丑了。希望对JavaScript初学者能有所帮助。你可以跟着作者一起做那些示例代码,等读完文章的时候,你就可以掌握JavaScript的基本操作了,你会发现其实这一切很容易。
Contents
Embedding and including
write and writeln
Document object
Message box
Function
Event handler
Form
Link
Date
Window
Frame
Embedding and including
Let's first see a simple example:
head >
title > This is a JavaScript example title >
script language ="JavaScript" >
script >
head >
body > Hi, man! body >
html >
Usually, JavaScript code starts with the tag and ends with the tag . The code placed between and . Sometimes, people embed the code in the tags:
head > head >
body >
script >

script >
body >
html >
Why do we place JavaScript code inside comment fields <!--
and //-->
?
It's for ensuring that the Script is not displayed by old browsers that do not support JavaScript. This is optional, but considered good practice. The LANGUAGE attribute also is optional, but recommended. You may specify a particular version of JavaScript:
You can use another attribute SRC to include an external file containing JavaScript code:
For example, shown below is the code of the external file hello.js :
The external file is simply a text file containing JavaScript code with the file name extension ".js".
Note:
- Including an external file only functions reliably across platforms n the version 4 browsers.
- The code can't include tags and , or you will get an error message.
write and writeln
In order to output text in JavaScript you must use write() or writeln(). Here's an example:
HEAD >
TITLE > Welcome to my site TITLE > HEAD >
BODY >
SCRIPT LANGUAGE ="JAVASCRIPT" >
SCRIPT >
BODY >
HTML >
Note: the document object write is in lowercase as JavaScript is case sensitive. The difference between write and writeln is: write just outputs a text, writeln outputs the text and a line break.
Document object
The document object is one of the most important objects of JavaScript. Shown below is a very simple JavaScript code:
In this code, document is the object. write is the method of this object. Let's have a look at some of the other methods that the document object possesses.
lastModified
You can always include the last update date on your page by using the following code:document.write( " This page created by John N. Last update: " + document.lastModified);
script >
All you need to do here is use the lastModified property of the document. Notice that we used
<font color="#0000ff">+</font>
to put together This page created by John N. Last update: and document.write.
bgColor and fgColor
Lets try playing around with bgColor and fgColor:document.bgColor = " black "
document.fgColor = " #336699 "
script >
Message Box
alert
There are three message boxes: alert, confirm, and prompt. Let's look at the first one:script >
window.alert( " Welcome to my site! " )
script >
body >
You can put whatever you want inside the quotation marks.
confirm
An example for confirm box:prompt
Prompt box is used to allow a user to enter something according the promotion:In all our examples above, we wrote the box methods as window.alert(). Actually, we could simply write the following instead as:
confirm()
prompt()
Variables and Conditions
Let's see an example:
var x = window.confirm( " Are you sure you want to quit " )
if (x)
window.alert( " Thank you. " )
else
window.alert( " Good choice. " )
script >
There are several concepts that we should know. First of all, var x = is a variable declaration. If you want to create a variable, you must declare the variable using the var statement. x will get the result, namely, true or false . Then we use a condition statement if else to give the script the ability to choose between two paths, depending on this result (condition for the following action). If the result is true (the user clicked "ok"), "Thank you" appears in the window box. If the result is false (the user clicked "cancel"), "Good choice" appears in the window box instead. So we can make more complex boxes using var, if and those basic methods.
var y = window.prompt( " please enter your name " )
window.alert(y)
script >
Another example:
script >
var x = confirm( " Are you sure you want to quit? " )
if ( ! x)
window.location = " http://www.yahoo.com "
script >
head >
body >
Welcome to my website!.
body > html >
If you click "cancel", it will take you to yahoo, and clicking ok will continue with the loading of the current page "Welcome to my website!". Note: if(!x) means: if click "cancel". In JavaScript, the exclamation mark !means: "none".
Function
Functions are chunks of code.Let's create a simple function:
{
document.write("Hello can you see me?")
}
Note that if only this were within your <script> </script> tags, you will not see "Hello can you see me?" on your screen because functions are not executed by themselves until you call upon them. So we should do something:
{
document.write("Hello can you see me?")
}
test()
Last line test() calls the function, now you will see the words "Hello can you see me?".
Event handler
What are event handlers? They can be considered as triggers that execute JavaScript when something happens, such as click or move your mouse over a link, submit a form etc.
onClick
onClick handlers execute something only when users click on buttons, links, etc. Let's see an example:function ss()
{
alert( " Thank you! " )
}
script >
form >
input type ="button" value ="Click here" onclick ="ss()" >
form >
The function ss() is invoked when the user clicks the button. Note: Event handlers are not added inside the <script></script> tags, but rather, inside the html tags.
onLoad
The onload event handler is used to call the execution of JavaScript after loading:frameset onload ="ss()" >
img src ="whatever.gif" onload ="ss()" >
onMouseover,onMouseout
These handlers are used exclusively with links.a href ="#" onMouseOut ="alert('Good try!')" > Get Out Here! a >
onUnload
onUnload executes JavaScript while someone leaves the page. For example to thank users.Handle multiple actions
How do you have an event handler call multiple functions/statements? That's simple. You just need to embed the functions inside the event handler as usual, but separate each of them using a semicolon:input type ="button" value ="Click here!" onClick ="alert('Thanks for visiting my site!');window.location='http://www.yahoo.com'" >
form >
Form
Let's say you have a form like this:
input type ="text" size ="10" value ="" name ="bb" > br >
input type ="button" value ="Click Here" onclick ="alert(document.aa.bb.value)" >
form >
Notice that we gave the names to the form and the element. So JavaScript can gain access to them.
onBlur
If you want to get information from users and want to check each element (ie: user name, password, email) individually, and alert the user to correct the wrong input before moving on, you can use onBlur. Let's see how onBlur works:head >
script >
function emailchk()
{
var x = document.feedback.email.value
if (x.indexOf( " @ " ) ==- 1 )
{
alert( " It seems you entered an invalid email address. " )
document.feedback.email.focus()
}
}
script >
head >
body >
form
name ="feedback" >
Email: input type ="text" size ="20" name ="email"
onblur ="emailchk()" > br >
Comment: textarea name ="comment" rows ="2" cols ="20" > textarea > br >
input type ="submit" value ="Submit" >
form >
body >
html >
If you enter an email address without the @, you'll get an alert asking you to re-enter the data . What is: x.indexOf("@")==-1? This is a method that JavaScript can search every character within a string and look for what we want. If it finds it will return the position of the char within the string. If it doesn't, it will return -1. Therefore, x.indexOf("@")==-1basically means: "if the string doesn't include @, then:
document.feedback.email.focus()
What's focus() ? This is a method of the text box, which basically forces the cursor to be at the specified text box. onsubmit
Unlike onblur, onsubmit handler is inserted inside the tag, and not inside any one element. Lets do an example: script >
input type ="text" size ="20" name ="userName" >
input type ="text" size ="20" name ="password" >
input type ="submit" name ="submit" value ="Submit" >
form >
Note:
if(document.login.userName.value=="").This means "If the box named userName of the form named login contains nothing, then...". return false. This is used to stop the form from submitting. By default, a form will return true if submitting. return validate() That means, "if submitting, then call the function validate()
"
. Protect a file by using Login
Let's try an exampleSCRIPT Language ="JavaScript" >
function checkLogin(x)
{
if ((x.id.value != " Sam " ) || (x.pass.value != " Sam123 " ))
{
alert( " Invalid Login " );
return false ;
}
else
location = " main.htm "
}
script >
form >
p > UserID: input type ="text" name ="id" > p >
p > Password: input type ="password" name ="pass" > p >
p > input type ="button" value

Les différences de performance et d'efficacité entre Python et JavaScript se reflètent principalement dans: 1) comme un langage interprété, Python fonctionne lentement mais a une efficacité de développement élevée et convient au développement rapide des prototypes; 2) JavaScript est limité au thread unique dans le navigateur, mais les E / S multi-threading et asynchrones peuvent être utilisées pour améliorer les performances dans Node.js, et les deux ont des avantages dans les projets réels.

JavaScript est originaire de 1995 et a été créé par Brandon Ike, et a réalisé que la langue en langue C. 1.C offre des capacités de programmation élevées et au niveau du système pour JavaScript. 2. La gestion de la mémoire de JavaScript et l'optimisation des performances reposent sur le langage C. 3. La fonctionnalité multiplateforme du langage C aide JavaScript à s'exécuter efficacement sur différents systèmes d'exploitation.

JavaScript s'exécute dans les navigateurs et les environnements Node.js et s'appuie sur le moteur JavaScript pour analyser et exécuter du code. 1) Générer une arborescence de syntaxe abstraite (AST) au stade d'analyse; 2) Convertir AST en bytecode ou code machine à l'étape de compilation; 3) Exécutez le code compilé à l'étape d'exécution.

Les tendances futures de Python et JavaScript incluent: 1. Python consolidera sa position dans les domaines de l'informatique scientifique et de l'IA, 2. JavaScript favorisera le développement de la technologie Web, 3. Le développement de plate-forme multiplié deviendra un sujet brûlant, et 4. L'optimisation des performances sera le focus. Les deux continueront d'étendre les scénarios d'application dans leurs champs respectifs et de faire plus de percées dans les performances.

Les choix de Python et JavaScript dans les environnements de développement sont importants. 1) L'environnement de développement de Python comprend Pycharm, Jupyternotebook et Anaconda, qui conviennent à la science des données et au prototypage rapide. 2) L'environnement de développement de JavaScript comprend Node.js, VScode et WebPack, qui conviennent au développement frontal et back-end. Le choix des bons outils en fonction des besoins du projet peut améliorer l'efficacité du développement et le taux de réussite du projet.

Oui, le noyau du moteur de JavaScript est écrit en C. 1) Le langage C fournit des performances efficaces et un contrôle sous-jacent, qui convient au développement du moteur JavaScript. 2) Prendre le moteur V8 comme exemple, son noyau est écrit en C, combinant l'efficacité et les caractéristiques orientées objet de C. 3) Le principe de travail du moteur JavaScript comprend l'analyse, la compilation et l'exécution, et le langage C joue un rôle clé dans ces processus.

JavaScript est au cœur des sites Web modernes car il améliore l'interactivité et la dynamicité des pages Web. 1) Il permet de modifier le contenu sans rafraîchir la page, 2) manipuler les pages Web via Domapi, 3) prendre en charge les effets interactifs complexes tels que l'animation et le glisser-déposer, 4) Optimiser les performances et les meilleures pratiques pour améliorer l'expérience utilisateur.

C et JavaScript réalisent l'interopérabilité via WebAssembly. 1) Le code C est compilé dans le module WebAssembly et introduit dans un environnement JavaScript pour améliorer la puissance de calcul. 2) Dans le développement de jeux, C gère les moteurs de physique et le rendu graphique, et JavaScript est responsable de la logique du jeu et de l'interface utilisateur.


Outils d'IA chauds

Undresser.AI Undress
Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover
Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool
Images de déshabillage gratuites

Clothoff.io
Dissolvant de vêtements AI

Video Face Swap
Échangez les visages dans n'importe quelle vidéo sans effort grâce à notre outil d'échange de visage AI entièrement gratuit !

Article chaud

Outils chauds

Télécharger la version Mac de l'éditeur Atom
L'éditeur open source le plus populaire

Version crackée d'EditPlus en chinois
Petite taille, coloration syntaxique, ne prend pas en charge la fonction d'invite de code

SublimeText3 version Mac
Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Navigateur d'examen sécurisé
Safe Exam Browser est un environnement de navigation sécurisé permettant de passer des examens en ligne en toute sécurité. Ce logiciel transforme n'importe quel ordinateur en poste de travail sécurisé. Il contrôle l'accès à n'importe quel utilitaire et empêche les étudiants d'utiliser des ressources non autorisées.

Adaptateur de serveur SAP NetWeaver pour Eclipse
Intégrez Eclipse au serveur d'applications SAP NetWeaver.
