Hello jQuery
=======
空白HTML頁面代碼, 僅僅載入了jquery.js庫.
<html><head> <script type="text/javascript" src="jquery-1.3.2.min.js"></script> <script type="text/javascript"> // we will add our javascript code here </script></head><body> <!-- we will add our HTML content here --></body></html>
下面這段代碼為document對象的ready事件註冊了一段事件處理代碼.
$(document).ready(function() { // do stuff when DOM is ready});
下面這段代碼的所作的事情是在document對象準備好了, 調用了ready事件的時候, 選擇當前document中所有的a對象(超連結對象), 並在a對象被點擊的時候彈出alert, 在其中輸出hello world.
$(document).ready(function() { $("a").click(function() { alert("Hello world!"); });});
注意這裡的$("a"), 這是一個jquery的選取器(selector).
符號'$'本身是jQuery裡"class"的別名, 所以$()會構造一個新的jQuery對象.
click()是jQuery對象的一個函數.
上面的一段代碼實際上是把click()事件綁定到了所有選擇了的元素(在這個例子裡僅是一個超連結元素)上, 並且在事件發生的時候執行我們提供的函數代碼.
上面的代碼相當於:
<a href="" onclick="alert('Hello world')">Link</a>
這二者的區別很明顯:
- 我們不需要在每一個元素上寫onclick了.
- 我們清晰地把結構(HTML)與行為(JS)分開了, 跟我們把結構(HTML)與展現(CSS)分開一樣.
來源:
Tutorials:Getting Started with jQuery
http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery