javascript常用方法總結

來源:互聯網
上載者:User

javascript常用方法總結

 1、JavaScript:寫入 HTML 輸出

 

 代碼如下:


document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph</p>");

 

2、JavaScript:對事件作出反應

 

 代碼如下:


<button type="button" onclick="alert('Welcome!')">點擊這裡</button>

 

3、JavaScript:改變 HTML 內容

 

代碼如下:


x=document.getElementById("demo") //尋找元素
x.innerHTML="Hello JavaScript"; //改變內容

 

4、JavaScript:改變 HTML 映像

 

 代碼如下:


element=document.getElementById('myimage')
element.src="../i/eg_bulboff.gif";

 

5、改變 HTML 樣式

 

 代碼如下:


x=document.getElementById("demo") //找到元素
x.style.color="#ff0000"; //改變樣式

 

6、JavaScript 對大小寫敏感。

JavaScript 對大小寫是敏感的。
當編寫 JavaScript 語句時,請留意是否關閉大小寫切換鍵。
函數 getElementById 與 getElementbyID 是不同的。
同樣,變數 myVariable 與 MyVariable 也是不同的。

7、提示:一個好的編程習慣是,在代碼開始處,統一對需要的變數進行聲明。

8、Value = undefined

在電腦程式中,經常會聲明無值的變數。未使用值來聲明的變數,其值實際上是 undefined。在執行過以下語句後,變數 carname 的值將是 undefined:
var carname;

9、建立 JavaScript 對象
本例建立名為 "person" 的對象,並為其添加了四個屬性:

 

複製代碼 代碼如下:


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

 

10、JavaScript 表單驗證

必填(或必選)項目
下面的函數用來檢查使用者是否已填寫表單中的必填(或必選)項目。假如必填或必選項為空白,那麼警告框會彈出,並且函數的傳回值為 false,否則函數的傳回值則為 true(意味著資料沒有問題):

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

<html>

<head>

<script type="text/javascript">

 

function validate_required(field,alerttxt)

{

with (field)

{

if (value==null||value=="")

{alert(alerttxt);return false}

else {return true}

}

}

 

function validate_form(thisform)

{

with (thisform)

{

if (validate_required(email,"Email must be filled out!")==false)

{email.focus();return false}

}

}

</script>

</head>

 

<body>

<form action="submitpage.htm" onsubmit="return validate_form(this)" method="post">

Email: <input type="text" name="email" size="30">

<input type="submit" value="Submit">

</form>

</body>

 

</html>

以上所述就是本文的全部內容了,希望大家能夠喜歡

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.