suchen
HeimWeb-Frontendjs-TutorialJavaScript For Beginners(转载)_基础知识

注:我对原文进行了编辑,对一些词汇标注颜色,方便阅读。本来准备翻译,但是觉得文章简单易懂,而且原文写得很好,所以就不献丑了。希望对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:  

html >
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:

html >
head > head >
body >
script >
""..
//  The code embedded in the  tags.
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:  

script  language ="JavaScript1.2" >

You can use another attribute SRC to include an external file containing JavaScript code: 

script  language ="JavaScript"  src ="hello.js" > script >

For example, shown below is the code of the external file hello.js :

document.write("Hello World!")

The external file is simply a text file containing JavaScript code with the file name extension ".js".

Note:

  1. Including an external file only functions reliably across platforms n the version 4 browsers.
  2. 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:

HTML >
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:  

document.write("Hi there.")

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:      

script  language ="JavaScript" >
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

script >
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:
 
 
body >
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: 

window.confirm("Are you sure you want to quit?") 

prompt

Prompt box is used to allow a user to enter something according the promotion: 
 
window.prompt("please enter user name") 

In all our examples above, we wrote the box methods as window.alert(). Actually, we could simply write the following instead as:      
 
alert()
confirm()
prompt()


Variables and Conditions

Let's see an example:   

script >
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.

script >
var  y = window.prompt( " please enter your name " )
window.alert(y)
script >

Another example:    

html > head >
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: 

function test()
{
   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:   
  
 

function test()
{
   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:

script >
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:   

body  onload ="ss()" >
frameset  onload ="ss()" >
img  src ="whatever.gif"  onload ="ss()" >

onMouseover,onMouseout

These handlers are used exclusively with links.

href ="#"  onMouseOver ="document.write('Hi, nice to see you!" > Over Here! a >
href ="#"  onMouseOut ="alert('Good try!')" > Get Out Here! a >

onUnload

onUnload executes JavaScript while someone leaves the page. For example to thank users. 

body  onunload ="alert('Thank you for visiting us. See you soon')" >

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: 

form >
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:   

form  name ="aa" >
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: 

html >
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: 

alert("It seems you entered an invalid email address.")
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. onsubmitUnlike onblur, onsubmit handler is inserted inside the
 tag, and not inside any one element. Lets do an example:
   

script >

script >

form  name ="login"  onsubmit ="return validate()" >
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 example 

html > head >
SCRIPT  Language ="JavaScript" >
function  checkLogin(x)
{
if  ((x.id.value  !=   " Sam " ) || (x.pass.value  != " Sam123 "
))
{
    alert(
" Invalid Login "
);
    
return   false
;
}
else

    location
= " main.htm "
}
script >

head > body >
form >
p > UserID: input  type ="text"  name ="id" > p >
p > Password: input  type ="password"  name ="pass" > p >
p > input  type ="button"  value
Stellungnahme
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
JavaScript -Frameworks: Stromversorgung moderner WebentwicklungJavaScript -Frameworks: Stromversorgung moderner WebentwicklungMay 02, 2025 am 12:04 AM

Die Kraft des JavaScript -Frameworks liegt in der Vereinfachung der Entwicklung, der Verbesserung der Benutzererfahrung und der Anwendungsleistung. Betrachten Sie bei der Auswahl eines Frameworks: 1. Projektgröße und Komplexität, 2. Teamerfahrung, 3. Ökosystem und Community -Unterstützung.

Die Beziehung zwischen JavaScript, C und BrowsernDie Beziehung zwischen JavaScript, C und BrowsernMay 01, 2025 am 12:06 AM

Einführung Ich weiß, dass Sie es vielleicht seltsam finden. Was genau muss JavaScript, C und Browser tun? Sie scheinen nicht miteinander verbunden zu sein, aber tatsächlich spielen sie eine sehr wichtige Rolle in der modernen Webentwicklung. Heute werden wir die enge Verbindung zwischen diesen drei diskutieren. In diesem Artikel erfahren Sie, wie JavaScript im Browser ausgeführt wird, die Rolle von C in der Browser -Engine und wie sie zusammenarbeiten, um das Rendern und die Interaktion von Webseiten voranzutreiben. Wir alle kennen die Beziehung zwischen JavaScript und Browser. JavaScript ist die Kernsprache der Front-End-Entwicklung. Es läuft direkt im Browser und macht Webseiten lebhaft und interessant. Haben Sie sich jemals gefragt, warum Javascr

Node.js Streams mit TypeScriptNode.js Streams mit TypeScriptApr 30, 2025 am 08:22 AM

Node.js zeichnet sich bei effizienten E/A aus, vor allem bei Streams. Streams verarbeiten Daten inkrementell und vermeiden Speicherüberladung-ideal für große Dateien, Netzwerkaufgaben und Echtzeitanwendungen. Die Kombination von Streams mit der TypeScript -Sicherheit erzeugt eine POWE

Python vs. JavaScript: Leistung und EffizienzüberlegungenPython vs. JavaScript: Leistung und EffizienzüberlegungenApr 30, 2025 am 12:08 AM

Die Unterschiede in der Leistung und der Effizienz zwischen Python und JavaScript spiegeln sich hauptsächlich in: 1 wider: 1) Als interpretierter Sprache läuft Python langsam, weist jedoch eine hohe Entwicklungseffizienz auf und ist für eine schnelle Prototypentwicklung geeignet. 2) JavaScript ist auf einen einzelnen Thread im Browser beschränkt, aber Multi-Threading- und Asynchronen-E/A können verwendet werden, um die Leistung in Node.js zu verbessern, und beide haben Vorteile in tatsächlichen Projekten.

Die Ursprünge von JavaScript: Erforschung seiner ImplementierungsspracheDie Ursprünge von JavaScript: Erforschung seiner ImplementierungsspracheApr 29, 2025 am 12:51 AM

JavaScript stammt aus dem Jahr 1995 und wurde von Brandon Ike erstellt und realisierte die Sprache in C. 1.C-Sprache bietet Programmierfunktionen auf hoher Leistung und Systemebene für JavaScript. 2. Die Speicherverwaltung und die Leistungsoptimierung von JavaScript basieren auf C -Sprache. 3. Die plattformübergreifende Funktion der C-Sprache hilft JavaScript, auf verschiedenen Betriebssystemen effizient zu laufen.

Hinter den Kulissen: Welche Sprache macht JavaScript?Hinter den Kulissen: Welche Sprache macht JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript wird in Browsern und Node.js -Umgebungen ausgeführt und stützt sich auf die JavaScript -Engine, um Code zu analysieren und auszuführen. 1) abstrakter Syntaxbaum (AST) in der Parsenstufe erzeugen; 2) AST in die Kompilierungsphase in Bytecode oder Maschinencode umwandeln; 3) Führen Sie den kompilierten Code in der Ausführungsstufe aus.

Die Zukunft von Python und JavaScript: Trends und VorhersagenDie Zukunft von Python und JavaScript: Trends und VorhersagenApr 27, 2025 am 12:21 AM

Zu den zukünftigen Trends von Python und JavaScript gehören: 1. Python wird seine Position in den Bereichen wissenschaftlicher Computer und KI konsolidieren. JavaScript wird die Entwicklung der Web-Technologie fördern. Beide werden die Anwendungsszenarien in ihren jeweiligen Bereichen weiter erweitern und mehr Durchbrüche in der Leistung erzielen.

Python vs. JavaScript: Entwicklungsumgebungen und ToolsPython vs. JavaScript: Entwicklungsumgebungen und ToolsApr 26, 2025 am 12:09 AM

Sowohl Python als auch JavaScripts Entscheidungen in Entwicklungsumgebungen sind wichtig. 1) Die Entwicklungsumgebung von Python umfasst Pycharm, Jupyternotebook und Anaconda, die für Datenwissenschaft und schnelles Prototyping geeignet sind. 2) Die Entwicklungsumgebung von JavaScript umfasst Node.JS, VSCODE und WebPack, die für die Entwicklung von Front-End- und Back-End-Entwicklung geeignet sind. Durch die Auswahl der richtigen Tools nach den Projektbedürfnissen kann die Entwicklung der Entwicklung und die Erfolgsquote der Projekte verbessert werden.

See all articles

Heiße KI -Werkzeuge

Undresser.AI Undress

Undresser.AI Undress

KI-gestützte App zum Erstellen realistischer Aktfotos

AI Clothes Remover

AI Clothes Remover

Online-KI-Tool zum Entfernen von Kleidung aus Fotos.

Undress AI Tool

Undress AI Tool

Ausziehbilder kostenlos

Clothoff.io

Clothoff.io

KI-Kleiderentferner

Video Face Swap

Video Face Swap

Tauschen Sie Gesichter in jedem Video mühelos mit unserem völlig kostenlosen KI-Gesichtstausch-Tool aus!

Heiße Werkzeuge

MantisBT

MantisBT

Mantis ist ein einfach zu implementierendes webbasiertes Tool zur Fehlerverfolgung, das die Fehlerverfolgung von Produkten unterstützen soll. Es erfordert PHP, MySQL und einen Webserver. Schauen Sie sich unsere Demo- und Hosting-Services an.

SAP NetWeaver Server-Adapter für Eclipse

SAP NetWeaver Server-Adapter für Eclipse

Integrieren Sie Eclipse mit dem SAP NetWeaver-Anwendungsserver.

SublimeText3 chinesische Version

SublimeText3 chinesische Version

Chinesische Version, sehr einfach zu bedienen

MinGW – Minimalistisches GNU für Windows

MinGW – Minimalistisches GNU für Windows

Dieses Projekt wird derzeit auf osdn.net/projects/mingw migriert. Sie können uns dort weiterhin folgen. MinGW: Eine native Windows-Portierung der GNU Compiler Collection (GCC), frei verteilbare Importbibliotheken und Header-Dateien zum Erstellen nativer Windows-Anwendungen, einschließlich Erweiterungen der MSVC-Laufzeit zur Unterstützung der C99-Funktionalität. Die gesamte MinGW-Software kann auf 64-Bit-Windows-Plattformen ausgeführt werden.

Sicherer Prüfungsbrowser

Sicherer Prüfungsbrowser

Safe Exam Browser ist eine sichere Browserumgebung für die sichere Teilnahme an Online-Prüfungen. Diese Software verwandelt jeden Computer in einen sicheren Arbeitsplatz. Es kontrolliert den Zugriff auf alle Dienstprogramme und verhindert, dass Schüler nicht autorisierte Ressourcen nutzen.