注:我对原文进行了编辑,对一些词汇标注颜色,方便阅读。本来准备翻译,但是觉得文章简单易懂,而且原文写得很好,所以就不献丑了。希望对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
사용자로부터 정보를 얻고 싶고 각 요소(예: 사용자 이름, 비밀번호, 이메일)를 개별적으로 확인하고 사용자에게 경고하고 싶은 경우 계속 진행하기 전에 잘못된 입력을 수정하려면 onBlur를 사용할 수 있습니다. onBlur작동 방식을 살펴보겠습니다.머리 >
스크립트 >
함수 emailchk()
{
var x = document.feedback.email.value
if (x.indexOf( " @ " ) ==- 1 )
{
경보( " 잘못된 이메일 주소를 입력하신 것 같습니다. " )
document.feedback.email. 포커스()
}
}
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 >
양식 >
p > 사용자 ID: 입력 유형 ="텍스트" 이름 ="id" > p >
p > 비밀번호: 입력 유형 ="password" 이름 ="pass" > p >
p > 입력 유형 ="버튼" 값

Node.js는 크림 덕분에 효율적인 I/O에서 탁월합니다. 스트림은 메모리 오버로드를 피하고 큰 파일, 네트워크 작업 및 실시간 애플리케이션을위한 메모리 과부하를 피하기 위해 데이터를 점차적으로 처리합니다. 스트림을 TypeScript의 유형 안전과 결합하면 Powe가 생성됩니다

파이썬과 자바 스크립트 간의 성능과 효율성의 차이는 주로 다음과 같이 반영됩니다. 1) 해석 된 언어로서, 파이썬은 느리게 실행되지만 개발 효율이 높고 빠른 프로토 타입 개발에 적합합니다. 2) JavaScript는 브라우저의 단일 스레드로 제한되지만 멀티 스레딩 및 비동기 I/O는 Node.js의 성능을 향상시키는 데 사용될 수 있으며 실제 프로젝트에서는 이점이 있습니다.

JavaScript는 1995 년에 시작하여 Brandon Ike에 의해 만들어졌으며 언어를 C로 실현했습니다. 1.C Language는 JavaScript의 고성능 및 시스템 수준 프로그래밍 기능을 제공합니다. 2. JavaScript의 메모리 관리 및 성능 최적화는 C 언어에 의존합니다. 3. C 언어의 크로스 플랫폼 기능은 자바 스크립트가 다른 운영 체제에서 효율적으로 실행하는 데 도움이됩니다.

JavaScript는 브라우저 및 Node.js 환경에서 실행되며 JavaScript 엔진을 사용하여 코드를 구문 분석하고 실행합니다. 1) 구문 분석 단계에서 초록 구문 트리 (AST)를 생성합니다. 2) 컴파일 단계에서 AST를 바이트 코드 또는 기계 코드로 변환합니다. 3) 실행 단계에서 컴파일 된 코드를 실행하십시오.

Python 및 JavaScript의 미래 추세에는 다음이 포함됩니다. 1. Python은 과학 컴퓨팅 분야에서의 위치를 통합하고 AI, 2. JavaScript는 웹 기술의 개발을 촉진하고, 3. 교차 플랫폼 개발이 핫한 주제가되고 4. 성능 최적화가 중점을 둘 것입니다. 둘 다 해당 분야에서 응용 프로그램 시나리오를 계속 확장하고 성능이 더 많은 혁신을 일으킬 것입니다.

개발 환경에서 Python과 JavaScript의 선택이 모두 중요합니다. 1) Python의 개발 환경에는 Pycharm, Jupyternotebook 및 Anaconda가 포함되어 있으며 데이터 과학 및 빠른 프로토 타이핑에 적합합니다. 2) JavaScript의 개발 환경에는 Node.js, VScode 및 Webpack이 포함되어 있으며 프론트 엔드 및 백엔드 개발에 적합합니다. 프로젝트 요구에 따라 올바른 도구를 선택하면 개발 효율성과 프로젝트 성공률이 향상 될 수 있습니다.

예, JavaScript의 엔진 코어는 C로 작성되었습니다. 1) C 언어는 효율적인 성능과 기본 제어를 제공하며, 이는 JavaScript 엔진 개발에 적합합니다. 2) V8 엔진을 예를 들어, 핵심은 C로 작성되며 C의 효율성 및 객체 지향적 특성을 결합하여 C로 작성됩니다.

JavaScript는 웹 페이지의 상호 작용과 역학을 향상시키기 때문에 현대 웹 사이트의 핵심입니다. 1) 페이지를 새로 고치지 않고 콘텐츠를 변경할 수 있습니다. 2) Domapi를 통해 웹 페이지 조작, 3) 애니메이션 및 드래그 앤 드롭과 같은 복잡한 대화식 효과를 지원합니다. 4) 성능 및 모범 사례를 최적화하여 사용자 경험을 향상시킵니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

DVWA
DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

맨티스BT
Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경
