2009年2月12日 星期四

[jQuery] jQuery 初體驗

第一支 jQuery 程式

很久之前就聽過 jQuery 的大名啦!

所以來試試看這個 JavaScript Framwork 到底厲害之處在哪裡..........

之前在查詢 JavaScript framework 的時候就有大概瞭解到,jQuery 的強項在於 DOM 的處理,據用過的人說,jQuery 處理 DOM 可是又快又簡單,是否真的有這麼神奇呢?

官網 tutorial 中的第一隻程式就有一些 DOM 的簡單應用:
<html>
<head>

<script type="text/javascript" src="js/jquery-1.3.1.js"></script>

<script type="text/javascript">
<!--
$(document).ready(function(){
/* 預設按下超連結都會執行以下的效果 */
$("a").click(function(event){
alert("Thanks for visiting!");

//透過 event 的 preventDefault() 方法,停止原本要做的動作(網頁導向指定頁面)
event.preventDefault();

//將此 object 隱藏(有慢慢隱藏的效果)
$(this).hide("slow");
});

//幫每一個 hyperlink 都加上 css 效果(對應到上方程式中定義的粗體)
$("a").addClass("test");

/* 由於 jQuery 的 function 都會回傳原本的 query object,因此可以將程式串在一起執行
因此以下程式執行的工作為:
1、按下超連結時,搜尋 class 名稱���否為 "clickme",若���,執行以下工作:
1.1 顯示 "Thanks for visiting!" 訊息 (上面已經定義過的動作會照樣進行)
1.2 開始慢慢消失
1.3 顯示 "you are leaving the site." 訊息
1.4 由於顯示訊息的關係(花了點時間),會讓超連結一瞬間消失(其實它���慢慢消失的)
2、使用 end() 方法,回到開始進行 query 的 document object(原本��� hyperlink object)
3、按下超連結時,搜尋 class 名稱���否為 "hideme",若���,執行以下工作:
3.1 顯示 "Thanks for visiting!" 訊息 (上面已經定義過的動作會照樣進行)
3.2 開始慢慢消失(這裡不寫 hide 也行,因為上面已經用過)
3.3 回傳 false
4、最後又使用 end() 方法,回到開始進行 query 的 document object
*/

$("a").filter(".clickme").click(function(){
alert("you are leaving the site.");
}).end().filter(".hideme").click(function(){
$(this).hide();
return false;
}).end();
});
-->
</script>

<style type="text/css">
a.test { font-weight: bold; }
</style>

</head>
<body>
<a href="http://jquery.com/">jQuery</a>
<p />
<a href="http://google.com/" class="clickme">I give a message when you leave</a>
<p />
<a href="http://yahoo.com/" class="hideme">Click me to hide!</a>
<p />
<a href="http://microsoft.com">I'm a normal link</a>
</body>
</html>



Event Regist
<html>                                                               
<head>
<script type="text/javascript" src="js/jquery-1.3.1.js"></script>
<script type="text/javascript">
<!--
$(document).ready(function(){
alert("document is ready!");

/* $ 符號代表的意義為 jQuery class
$("a") 屬於 jQuery selector
並註冊了 click 的事件(事件的註冊會累計執行) */

$("a").click(function(){
alert("Hello World!");
});
/* 透過此種方式進行 event regist
就不用在每個 element 中撰寫類似「<a href="" onclick="alert('Hello world')">Link</a>」的語法了
這樣最大的優點是:「HTML、JavaScript、CSS 都可以徹底的分離了!」 */

-->
</script>
</head>
<body>
<a href="">Link</a>
</body>
</html>
使用 selector $("元素名稱") 選擇特定的 element,並進行 event regist。 (範例中註冊的是 click 事件)

透過 jQuery 的 event regist 方式,就可以作到將 HTML、JavaScript、CSS 三個徹底分離,讓後續管理更簡單方便。



Selector 的應用
<html>                                                               
<head>
<script type="text/javascript" src="js/jquery-1.3.1.js"></script>
<script type="text/javascript">
<!--
$(document).ready(function(){
//尋找 ID 為 orderedlist 的 element,並增加 css 效果
$("#orderedlist").addClass("red");

//尋找 orderedlist 的 li element,並增加 css 效果
$("#orderedlist > li").addClass("blue");

//尋找 orderlist 中最後一個 li element,並註冊 hover 事件,指定發生的 css 效果
$("#orderedlist li:last").hover(function(){
$(this).addClass("green");
}, function(){
$(this).removeClass("green");
});

/* 尋找 ID 為 orderedlist 的 element
並在其所有的 li element 加上字串
而「$("#orderedlist").find("li")」的效果等同「$("#orderedlist > li")」*/

$("#orderedlist").find("li").each(function(i){
$(this).append(" BAM! " + i);
});
});
-->
</script>

</head>
<body>
<ol id="orderedlist">
<li>First element</li>
<li>Second element</li>
<li>Third element</li>
</ol>
</body>
</html>
  1. 使用 css + xpath 結合的方式尋找 element,例如範例中的「$("#orderedlist > li")」以及「$("#orderedlist li:last")

  2. 使用 each 在每個 element 後方在另外加上字串

<html>                                                               
<head>
<script type="text/javascript" src="js/jquery-1.3.1.js"></script>
<script type="text/javascript">
<!--
$(document).ready(function(){
//尋找不包含 ul 的 li element,並指定 css 效果
$("li").not(":has(ul)").css("border", "1px solid black");
});
-->
</script>

</head>
<body>
<ol id="orderedlist">
<li>First element</li>
<li>Second element</li>
<li>Third element</li>
</ol>

<ol id="orderedlist2">
<li>First element, second list</li>
<li>Second element, second list</li>
<li>Third element, second list</li>
<li>Li with child ul
<ul>
<li>Child One</li>
<li>child two</li>
</ul>
</li>
</ol>
</body>
</html>
  1. 透過 not(expr):has(selector) 的搭配,取得不包含 ul 的 li element

  2. 使用 css(name, value) 指定 css 效果

<html>                                                               
<head>
<script type="text/javascript" src="js/jquery-1.3.1.js"></script>
<script type="text/javascript">
<!--
$(document).ready(function(){
$("a[name]").css("background-color", "#bbb");
});
-->
</script>

</head>
<body>
<a href="">no name attribute</a>
<p />
<a name="test" href="">has name attribute</a>
</body>
</html>
透過 element[attribute_name] 的方式取得擁有特定 attribute 的元素

<html>                                                               
<head>
<script type="text/javascript" src="js/jquery-1.3.1.js"></script>
<script type="text/javascript">
<!--
$(document).ready(function(){
/* 一連串的動作,說明如下:
1、尋找 ID 為 FAQ 的 element
2、尋找該 element 下的 dd element,並將其隱藏
3、使用 end() 回到 faq element 狀態
4、繼續尋找 dt element,並進行 event regist
5、設定 click 後,會讓 dt element 的下一個 element 進行 slideToggle() 的動作 */

$("#faq").find('dd').hide().end().find('dt').click(function(){
$(this).next().slideToggle();
});
//使用 end() 的優點在於 $("#faq") 僅會發生一次 DOM select
});
-->
</script>

</head>
<body>
<h3>Bird FAQ - click the questions to show the answers</h3>
<dl id="faq">
<dt>What shouldn't I do to the bird?</dt>
<dd>Never use oils or lotions which contain oils on your bird. They gunk up the feathers,
and ruin their insulating properties. This means a chilled bird. Never wait out a cat bite--those
require immediate veterinary attention--a bird can die within two days because a cat'
s mouth is so
filthy and full of bacteria. Don't bother with over-the-counter medication. It really doesn't work,
and in some cases, may upset the delicate bacterial balance in the bird's body, or even worsen the
situation. Never try to treat a fracture at home.</dd>

<dt>My bird is healthy. I don'
t need to go to a vet, do I?</dt>
<dd>Schedule a "well-bird" checkup. Prevention is the best medicine. Even though the bird might appear outwardly healthy, it may have a low-grade infection or something not so readily apparent. Your bird's health and your peace of mind will be worth it.</dd>

<dt>My bird'
s leg is being rubbed raw by the leg band. Can I take it off?</dt>
<dd>No. Don't attempt this, especially if the leg is broken or swollen. The vet will be able
to remove the band, and deal with whatever injury maybe lurking under the banded area.</dd>

<dt>How do I pull a broken blood feather?</dt>
<dd>This is probably the most common mishap. The remedy is simple--yank! It'
s most easily done
with two people. One to restrain the bird and the other to pull the feather. Use pliers, or a
hemostat. Tweezers won't work on primaries. Make certain that the wing bones are firmly supported
or you can break the wing. Clamp onto the feather and give a sharp tug in the direction of the
feather. The feather will come out. Next, apply gentle, direct pressure to the follicle where the
feather was to stop the bleeding. Dab some styptic powder on it, as it will help stop the bleeding
as well. Let the bird rest. Ask your vet or breeder to demonstrate exactly how to pull a blood
feather if you'
re apprehensive about doing it.</dd>
</dl>
</body>
</html>
  1. 透過 next() 可以取得 next sibling node

  2. 使用 end() 的優點在於 $("#faq") 的 DOM select 動作只會作一次,因此可以增加程式執行效能

  3. slideToggle() 就只是滑動的效果而已,不過官方文件中還可以另外指定 speed 跟 callback function

<html>                                                               
<head>
<script type="text/javascript" src="js/jquery-1.3.1.js"></script>
<script type="text/javascript">
<!--
$(document).ready(function(){
/* 一連串的動作,說明如下:
1、尋找 ID 為 FAQ 的 element
2、尋找該 element 下的 dd element,並將其隱藏
3、使用 end() 回到 faq element 狀態
4、繼續尋找 dt element,並進行 event regist
5、設定 click 後,會讓 dt element 的下一個 element 進行 slideToggle() 的動作 */

$("#faq").find('dd').hide().end().find('dt').click(function(){
$(this).next().slideToggle();
});
//使用 end() 的優點在於 $("#faq") 僅會發生一次 DOM select
});
-->
</script>

</head>
<body>
<h3>Bird FAQ - click the questions to show the answers</h3>
<dl id="faq">
<dt>What shouldn't I do to the bird?</dt>
<dd>Never use oils or lotions which contain oils on your bird. They gunk up the feathers,
and ruin their insulating properties. This means a chilled bird. Never wait out a cat bite--those
require immediate veterinary attention--a bird can die within two days because a cat'
s mouth is so
filthy and full of bacteria. Don't bother with over-the-counter medication. It really doesn't work,
and in some cases, may upset the delicate bacterial balance in the bird's body, or even worsen the
situation. Never try to treat a fracture at home.</dd>

<dt>My bird is healthy. I don'
t need to go to a vet, do I?</dt>
<dd>Schedule a "well-bird" checkup. Prevention is the best medicine. Even though the bird might appear outwardly healthy, it may have a low-grade infection or something not so readily apparent. Your bird's health and your peace of mind will be worth it.</dd>

<dt>My bird'
s leg is being rubbed raw by the leg band. Can I take it off?</dt>
<dd>No. Don't attempt this, especially if the leg is broken or swollen. The vet will be able
to remove the band, and deal with whatever injury maybe lurking under the banded area.</dd>

<dt>How do I pull a broken blood feather?</dt>
<dd>This is probably the most common mishap. The remedy is simple--yank! It'
s most easily done
with two people. One to restrain the bird and the other to pull the feather. Use pliers, or a
hemostat. Tweezers won't work on primaries. Make certain that the wing bones are firmly supported
or you can break the wing. Clamp onto the feather and give a sharp tug in the direction of the
feather. The feather will come out. Next, apply gentle, direct pressure to the follicle where the
feather was to stop the bleeding. Dab some styptic powder on it, as it will help stop the bleeding
as well. Let the bird rest. Ask your vet or breeder to demonstrate exactly how to pull a blood
feather if you'
re apprehensive about doing it.</dd>
</dl>
</body>
</html>
  1. 透過 parents(expr) 取得父節點,並指定 css 效果。



參考資料

沒有留言:

張貼留言