顯示具有 JavaScript 標籤的文章。 顯示所有文章
顯示具有 JavaScript 標籤的文章。 顯示所有文章

2009年7月4日 星期六

[JavaScript] 將JavaScript 物件轉為 json 字串

一般將物件轉為 json 字串都是在編譯式的程式語言中進行的! 而這次有需要宣告 JavaScript 物件並轉為 json 字串。

Google 了一下,發現已經有人提供寫好的 JavaScript Library 可以用啦!

以下有一段語法,包含 JavaScript 物件的宣告並搭配 jQuery 一同使用此 library:



參考資料


[jQuery] 引用外部 JS 檔

在使用 jQuery 時,有時會需要額外引用外部的 js 檔案來使用裡面的功能

要怎麼作呢?

以下有一段範例語法:


參考資料

javascript include javascript(使用jQuery) - cloudio™- 點部落


2009年2月20日 星期五

[JavaScript] expando 屬性的定義與使用

最近在讀 Learning Jquery 時,看見 JavaScript expando,是個蠻有意思的東西,可以自行擴充 JavaScript object 的屬性。

而由於這些屬性是放置於 memory 中,因此使用起來速度較快,不過也要記得釋放,免得出現 memory leak 的問題。

在網路上查詢到以下的範例(內容有稍作修改),說明 JavaScript expando 的使用方式:
<html>
<head>
<script type="text/javascript">
<!--
var myObj = new Object();
alert(myObj.toString()); //出現 "[object Object]"

//設定 expando 屬性
myObj.myExpando = "Hello Expando";
myObj.toString = function(){ //override toString() method
return this.myExpando;
}
alert(myObj.toString()); //出現 "Hello Expando"

//設定 expando 屬性
myObj.reportTime = function(){
alert(new Date());
}
myObj.reportTime(); //出現目前的日期與時間

//刪除 expando 屬性
delete myObj.reportTime;

//再一次嘗試呼叫已經刪除的 expando 屬性
try {
myObj.reportTime();
} catch(e) {
alert(e.message); //出現 "myObj.reportTime is not a function"
}
-->
</script>
</head>
<body>
</body>
</html>



參考資料

2009年2月12日 星期四

[jQuery] jQuery + AJAX

AJAX

AJAX,這個技術是透過 JavaScript 中的 XMLHttpRequest 物件去呼叫後端 server code 並動態改變前端的網頁,讓網頁不需要 refresh。

AJAX 的技術並不複雜,大概掌握幾個重點即可:
  1. XMLHttpRequest 物件將資料傳遞到後端 server 的方式,可分為 POST 與 GET。

  2. 從 server 回傳的資料可以是 plain text 或是 XML。

  3. 前端網頁 DOM 的處理........(這其實跟 AJAX 已經沒有太大關係了)



jQuery 與 AJAX 的搭配


直接寫 pure XMLHttpRequest 的程式碼真的太累了,光是 cross browser 的問題就可以搞死人了......不過還好 jQuery 都幫大家處理好啦!

以下用的範例程式來說明:(demo)

ajax01.html
<html>
<head>
<script type="text/javascript" src="js/jquery-1.3.1.js"></script>
<script type="text/javascript">
<!--
$(document).ready(function(){
//取得 button 物件並註冊 click 事件
$("#btnAJAX").click(function(){
//取得使用者輸入的值
var intValue = $("#txtValue").val();

/* 以 POST 的方式送出 request
傳入參數 : value
參數值 = intValue
callback function 為 function(result){...} */

$.post("server01.php", {value : intValue}, function(result){
$("#spnMain").html("server 端回傳結果 = " + result);
});
});
});
-->
</script>
</head>
<body>
請輸入整數值,server 會計算其平方值並回傳:<p />
<input type="text" id="txtValue" /> <input type="button" id="btnAJAX" value="從 server 端取得結果" /><p />
<span id="spnMain"></span>
</body>
</html>

server01.php
<?php
if(isset($_POST["value"]))
echo $_POST["value"] * $_POST["value"];
else
echo "0";
?>

從上面的範例可以看出,透過 jQuery 物件的 post() 方法就可以直接享受到 AJAX 的好處囉! 當然,也可以用 get() 的方式來達到 AJAX 的效果。

此外,callback function 的部份比較需要注意的就是參數的傳遞了,在 jQuery 中可以允許使用一般的方式或是 context 的方式傳入參數,以下用範例說明:(demo)

ajax02.html
<html>
<head>
<script type="text/javascript" src="js/jquery-1.3.1.js"></script>
<script type="text/javascript">
<!--
//測試函式
function testFunc(intVal) {
alert("final value is " + (intVal * 2 + 10));
} //end function


$(document).ready(function(){
//取得 button 物件並註冊 click 事件
$("#btnAJAX").click(function(){
//取得使用者輸入的值
var intValue = $("#txtValue").val();

/* 以 POST 的方式送出 request
傳入參數 : value
參數值 = intValue
callback function 為 function(result){...} */

$.post("server.php", {value : intValue}, function(result){
//直接呼叫 function
testFunc(result);

//使用 jQuery context 的方式呼叫 function
testFunc.apply(this, [result]);
});
});
});
-->
</script>
</head>
<body>
請輸入整數值,server 會計算其平方值並回傳:<p />
<input type="text" id="txtValue" /> <input type="button" id="btnAJAX" value="從 server 端取得結果" /><p />
<span id="spnMain"></span>
</body>
</html>


參考資料

[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 效果。



參考資料

2008年11月9日 星期日

如何在 Blogger 張貼漂亮的程式碼

在「版面配置」的「修改 HTML」中的「</body>」與「</html>」兩個標籤中加入以下 JavaScript 程式碼即可:
<!--  syntax highlighting -->

<link href="http://godleon.googlepages.com/SyntaxHighlighter.css" rel="stylesheet" type="text/css" />
<script src="http://godleon.googlepages.com/shCore.js" type="text/javascript" xml:space="preserve"/>
<script src="http://godleon.googlepages.com/shBrushJava.js" type="text/javascript" xml:space="preserve" />
<script src="http://godleon.googlepages.com/shBrushCss.js" type="text/javascript" xml:space="preserve" />
<script src="http://godleon.googlepages.com/shBrushXml.js" type="text/javascript" xml:space="preserve" />
<script src="http://godleon.googlepages.com/shBrushVb.js" type="text/javascript" xml:space="preserve" />
<script src="http://godleon.googlepages.com/shBrushSql.js" type="text/javascript" xml:space="preserve" />
<script src="http://godleon.googlepages.com/shBrushRuby.js" type="text/javascript" xml:space="preserve" />
<script src="http://godleon.googlepages.com/shBrushPython.js" type="text/javascript" xml:space="preserve" />
<script src="http://godleon.googlepages.com/shBrushPhp.js" type="text/javascript" xml:space="preserve" />
<script src="http://godleon.googlepages.com/shBrushJScript.js" type="text/javascript" xml:space="preserve" />
<script src="http://godleon.googlepages.com/shBrushDelphi.js" type="text/javascript" xml:space="preserve" />
<script src="http://godleon.googlepages.com/shBrushCSharp.js" type="text/javascript" xml:space="preserve" />
<script src="http://godleon.googlepages.com/shBrushCpp.js" type="text/javascript" xml:space="preserve" />

<script type="text/javascript" xml:space="preserve">
dp.SyntaxHighlighter.ClipboardSwf = 'http://godleon.googlepages.com/clipboard.swf';
dp.SyntaxHighlighter.BloggerMode();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

dp.SyntaxHighlighter.BloggerMode();
dp.SyntaxHighlighter.HighlightAll('code');

<!-- end of syntax highlighting -->

使用方式可以參考官方網站的說明喔!


參考資料

  1. Sjcywg's Blog!: Syntax Highlighting

  2. Ticore's Blog: 自改版 dp.SyntaxHighlighter 1.5.1.1

  3. Usage - syntaxhighlighter - Google Code - How to use SyntaxHighlighter.