位置: 编程技术 - 正文

JavaScript For Beginners(转载)

编辑:rootadmin

注:我对原文进行了编辑,对一些词汇标注颜色,方便阅读。本来准备翻译,但是觉得文章简单易懂,而且原文写得很好,所以就不献丑了。希望对JavaScript初学者能有所帮助。你可以跟着作者一起做那些示例代码,等读完文章的时候,你就可以掌握JavaScript的基本操作了,你会发现其实这一切很容易。

Contents Embedding and including write and writelnDocument object Message box Function Event handler Form Link Date Window Frame

Embedding and including

推荐整理分享JavaScript For Beginners(转载),希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:,内容如对您有帮助,希望把文章链接给更多的朋友!

Let's first see a simple example:

< html > < head > < title > This is a JavaScript example </ title > < script language ="JavaScript" > <!-- document.write( " Hello World! " );// --> </ script > </ head > < body > Hi, man! </ body > </ html >

Usually, JavaScript code starts with the tag <Script language="JavaScript"> and ends with the tag </script>. The code placed between <head> and </head>. Sometimes, people embed the code in the <body> tags:

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

Including an external file only functions reliably across platforms n the version 4 browsers. The code can't include tags <script language...> and </script>, 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" > <!-- document.write( " Welcome to my site! " );// --> </ 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 + 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 = " # " </ 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 = " " </ 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 JavaScript For Beginners(转载)

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> 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. < a href ="#" onMouseOver ="document.write('Hi, nice to see you!" > Over Here! </ a > < 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=' > </ form > Form

Let's say you have a form like this:

< form name ="aa" > < input type ="text" size ="" 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.valueif (x.indexOf( " @ " ) ==- 1 ){ alert( " It seems you entered an invalid email address. " ) document.feedback.email.focus()}}</ script ></ head >< body > < formname ="feedback" > Email: < input type ="text" size ="" name ="email" onblur ="emailchk()" >< br > Comment: < textarea name ="comment" rows ="2" cols ="" ></ 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 <form> tag, and not inside any one element. Lets do an example: < script > <!-- function validate(){if (document.login.userName.value == "" ){ alert ( " Please enter User Name " ) return false }if (document.login.password.value == "" ){ alert ( " Please enter Password " ) return false }}// --> </ script > < form name ="login" onsubmit ="return validate()" > < input type ="text" size ="" name ="userName" > < input type ="text" size ="" 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 != " Sam " )){ 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 ="Login" onClick ="checkLogin(this.form)" ></ p > </ form > </ body ></ html > || means "or", and , != indicates "not equal". So we can explain the script: "If the id does not equal 'Sam', or the password does not equal 'Sam', then show an alert ('Invalid Login') and stop submitting. Else, open the page 'main.htm'". Link

In most cases, a form can be repaced by a link:

< a href ="JavaScript:window.location.reload()" > Click to reload! </ a >

More examples:

< a href ="#" onClick ="alert('Hello, world!')" > Click me to say Hello </ a >< br > < a href ="#" onMouseOver ="location='main.htm'" > Mouse over to see Main Page </ a >

Date

Let's see an example:

< HTML >< HEAD >< TITLE > ShowDate </ TITLE ></ HEAD > < BODY > < SCRIPT LANGUAGE ="JavaScript" > var x = new Date();document.write (x);</ SCRIPT > </ BODY ></ HTML >

To activate a Date Object, you can do this: var x = new Date(). Whenever you want to create an instance of the date object, use this important word: new followed by the object name().

Dynamically display different pages You can display different pages according to the different time. Here is an example: var banTime= new Date()var ss=banTime.getHours()if (ss < = ) document.write("<img src ='banner1.gif' > ")else document.write(" < img src ='banner2.gif' > ") Date object Methods getDate getTimegetTimezoneOffsetgetDaygetMonthgetYear getSecondsgetMinutesgetHours Window

Open a window To open a window, simply use the method "window.open()": < form > < input type ="button" value ="Click here to see" onclick ="window.open('test.htm')" > </ form > You can replace test.htm with any URL, for example, with

Size, toolbar, menubar, scrollbars, location, status Let's add some of attributes to the above script to control the size of the window, and show: toolbar, scrollbars etc. The syntax to add attributes is: open("URL","name","attributes") For example: < form > < input type ="button" value ="Click here to see" onclick ="window.open('page2.htm','win1','width=,height=,menubar')" > </ form > Another example with no attributes turned on, except the size changed: < form > < input type ="button" value ="Click here to see" onclick ="window.open('page2.htm','win1','width=,height=')" > </ form > Here is the complete list of attributes you can add: width height toolbar location directories status scrollbars resizable menubar

Reload To reload a window, use this method: window.location.reload()

Close Window Your can use one of the codes shown below: < form > < input type ="button" value ="Close Window" onClick ="window.close()" > </ form > < a href ="javascript:window.close()" > Close Window </ a >

Loading The basic syntax when loading new content into a window is: window.location="test.htm" This is the same as < a href ="test.htm>Try this </a> Let's provide an example, where a confirm box will allow users to choose between going to two places: < script > <!-- function ss(){var ok = confirm('Click " OK " to go to yahoo, " CANCEL " to go to hotmail')if (ok)location = " " else location = " " }// --> </ script >

Remote Control Window Let's say you have opened a new window from the current window. After that, you will wonder how to make a control between the two windows. To do this, we need to first give a name to the window.Look at below: aa=window.open('test.htm','','width=,height=') By giving this window a name "aa", it will give you access to anything that's inside this window from other windows. Whenever we want to access anything that's inside this newly opened window, for example, to write to this window, we would do this: aa.document.write("This is a test.").

Now, let's see an example of how to change the background color of another window:

< html >< head >< title ></ title ></ head > < body > < form > < input type ="button" value ="Open another page" onClick ="aa=window.open('test.htm','','width=,height=')" > < input type ="radio" name ="x" onClick ="aa.document.bgColor='red'" > < input type ="radio" name ="x" onClick ="aa.document.bgColor='green'" > < input type ="radio" name ="x" onClick ="aa.document.bgColor='yellow'" > </ form > </ body ></ html >

opener Using "opener" property, we can access the main window from the newly opened window.

Let's create Main page:

< html > < head > < title ></ title > </ head > < body > < form > < input type ="button" value ="Open another page" onClick ="aa=window.open('test.htm','','width=,height=')" > </ form > </ body > </ html >

Then create Remote control page (in this example, that is test.htm):

< html > < head > < title ></ title > < script > function remote(url){window.opener.location = url}</ script > </ head > < body > < p >< a href ="#" onClick ="remote('file1.htm')" > File1 </ a ></ p > < p >< a href ="#" onClick ="remote('file2.htm')" > File2 </ a ></ p > </ body > </ html >

Try it now!

Frame

One of the most popular uses of loading multiple frames is to load and change the content of more than one frame at once. Lets say we have a parent frame:

< html > < frameset cols =",*" > < frame src ="page1.htm" name ="frame1" > < frame src ="page2.htm" name ="frame2" > </ frameset > </ html >

We can add a link in the child frame "frame1" that will change the contents of not only page1, but page2 too. Shown below is the html code for it:

< html > < body > < h2 > This is page 1 </ h2 > < a href ="page3.htm" onClick ="parent.frame2.location='page4.htm'" > Click Here </ a > </ body > </ html >

Notice: You should use "parent.frame2.location" to access another frame. "parent" standards for the parent frame containing the frameset code.Source:

javascript中的对象和数组的应用技巧 javascript已经用了有三年多了,但是对一些细节的东西还是一知半解,比如对象和数组,一直都在用一些最基本的操作。这是我学习的一个坏习惯--懒,

Javascript标准DOM Range操作全集第1/3页 2级DOM定义了一个createRange()方法,如果是按照DOM此标准的浏览器(IE并不是支持此标准的,但是IE里的属性或方法却远比标准中定义的多得多),它属于do

尽可能写"友好"的"Javascript"代码 在SearchEngine的robot搜索时,针对的type,text/html此类文本的友好度是最高的(现阶段text/xml除外),而text/javascript此类的友好度不理想,如果robot还要判断D

标签: JavaScript For Beginners(转载)

本文链接地址:https://www.jiuchutong.com/biancheng/385692.html 转载请保留说明!

上一篇:JavaScript的目的分析(javascript的主要功能)

下一篇:javascript 设计模式之单体模式 面向对象学习基础(js设计模型)

  • 抄税是什么意思谁做的事情
  • 水泥建材公司
  • 多计提个税怎么办
  • 累计缴税扣除额
  • 去年的成本如何调整汇算清缴额
  • 社保公司部分交多少比例
  • 商贸公司可以做美容行业吗?
  • 简易征收类型
  • 员工出差的住宿费计入什么科目
  • 借款利息是否可以转为本金
  • 仓储企业的成本有哪些
  • 销售预付卡的成本是什么
  • 供应商租赁企业资质要求
  • 发工资四舍五入可以吗
  • 计提工资和应付职工薪酬怎么不一样
  • 公司预付签证费怎么入账
  • 用银行存款上交各种税费
  • 用于文化活动费用的科目
  • 企业职工福利费扣除标准
  • 免税企业取得增值税专用发票怎么处理
  • 连号发票税务风险
  • 账本印花税怎么缴纳
  • 会务费能开发票吗
  • 税控盘超期还能清卡吗
  • 开票金额与实际金额差5元
  • 股东的房产无偿提供给公司用
  • 企业购买的土地计入无形资产
  • 清卡信息还未生成请稍后再试什么意思
  • 长期股权投资溢价购入
  • 计提代扣代缴个税
  • win11怎么回到10
  • 其他应付款结转什么科目
  • php怎么读取txt
  • 国有资产无偿划转协议
  • PHP:imagefilledpolygon()的用法_GD库图像处理函数
  • Bàu Cá Cái的红树林,越南广义 (© Robert Harding World Imagery/Offset)
  • php中execute
  • php中pdo
  • 送货上门需要其他费用吗
  • php取值
  • 增值税发票怎么抵税
  • 支付宝提现到对公账户怎么做账
  • css calculate
  • react roter
  • 电力系统培训计划
  • 物业管理公司的主管部门是哪个单位
  • 暂估入库有风险吗
  • mongodb如何修改数据
  • 什么叫动量交易
  • 零税率与免税有何区别
  • 资产减值损失的借贷方向
  • 支付宝付款,对方能看见是花呗还是银行卡么
  • 任意盈余公积金的用途
  • 付的房屋租金计入什么会计科目
  • 什么是企业所得税收入
  • 公司购买的家电怎么入账
  • 税控系统设备可以全额抵扣吗
  • 提交免税申请
  • 工程发票入账
  • 所有者权益的减少是什么意思
  • SQL 导入导出Excel数据的语句
  • windows server 2008 r2最大支持内存
  • Windows Server 2008中安装DNS服务器详细图文教程
  • Ubuntu 14.04/14.10如何安装记账软件HomeBank?
  • xp系统怎么装机
  • WebProxy.exe - WebProxy是什么进程
  • linux操作系统配置网络
  • 你会支持国产系统吗英文
  • opengl glu
  • javascript学习指南
  • mysql命令备份数据库
  • css控制html
  • vue list清空
  • 源码分析工具
  • js过滤特殊字符
  • 安卓小项目实战软件
  • 成都市老年公交卡年审地点
  • 自贡市税务局稽查局领导
  • 亳州契税补贴如何领取
  • 企业需要缴纳哪些费用
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

    网站地图: 企业信息 工商信息 财税知识 网络常识 编程技术

    友情链接: 武汉网站建设