JavaScript簡單入門基礎教程,javascript基礎教程

來源:互聯網
上載者:User

JavaScript簡單入門基礎教程,javascript基礎教程
1JavaScript嵌套在html中

         通常的做法是把函數放入<head> 部分中,或者放在頁面底部。這樣就可以把它們安置到同一處位置,不會干擾頁面的內容。

         以下是一個js驗證輸入是否為空白的代碼,自己可以在webroot建立一個html檔案測試。

<!DOCTYPE html>

<html>

<body>

 

<h1>我的第一段 JavaScript</h1>

 

<p>請輸入數字。如果輸入值不是數字,瀏覽器會彈出提示框。</p>

 

<input id="demo"type="text">

 

<script>

function myFunction()

{

varx=document.getElementById("demo").value;

if(x==""||isNaN(x))

         {

         alert("NotNumeric");

         }

}

</script>

 

<button type="button"onclick="myFunction()">點擊這裡</button>

 

</body>

</html>

 

當然也可以不用函數

 

<!DOCTYPE html>

<html>

<body>

 

<h1>My Web Page</h1>

 

<p id="demo">A Paragraph.</p>

 

<div id="myDIV">A DIV.</div>

 

<script>

document.getElementById("demo").innerHTML="HelloWorld";

document.getElementById("myDIV").innerHTML="Howare you?";

</script>

 

</body>

</html>

2JavaScript獨立於html檔案,檔案類型為*.js

<!DOCTYPE html>

<html>

<body>

<scriptsrc="myScript.js"></script>

</body>

</html>

myScript.js與jsp檔案或者檔案位於同一位置,也就是都位於webroot下面。當然,你也可以在webroot下面建立一個folder。

3外部js檔案怎麼寫4js檔案的常用函數介紹4.1擷取html元素內容
<script>
document.getElementById("demo").innerHTML="My First JavaScript";
</script>
4.2向介面輸出內容
<script>
document.write("<p>My First JavaScript</p>");
</script>
4.3寫注釋

直接向Java那樣,單行“//”即可,多行“/*   */”

4.4變數

不用像Java那樣,說明int,string類型。全部var。

包括物件類型。

person=new Object();
person.firstname="Bill";
person.lastname="Gates";
person.age=56;
person.eyecolor="blue";
4.5函數

函數和Java函數那樣,可以帶參數,也可以不帶,可以有返回值,也可以沒有。

一個函數可以調用另外一個函數的返回值。

在html檔案中

<button onclick="myFunction('Harry Potter','Wizard')">點擊這裡</button>
<button onclick="myFunction('Bob','Builder')">點擊這裡</button>

在js檔案中

<button onclick="myFunction('Bill Gates','CEO')">點擊這裡</button>
 
<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script>

下面給一個函數互相調用的例子

function myFunction()
{
var x=5;
return x;
}

另外一個函數中

var myVar=myFunction();

當然myVar的值為5

4.6退出函數

 

function myFunction(a,b)
{
if (a>b)
  {
  return;
  }
x=a+b
}

當a>b是退出函數

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.