2013年8月24日 星期六

jQuery : 初新者的第一步 ( Getting Start )


This is a basic tutorial, designed to help you get started using jQuery. If you don't have a test page setup yet, start by creating the following HTML page:
這個教程將協助你開始使用 jQuery。如果你沒有一個測試的網頁,那你可以透過下列的程式碼建立一個測試網頁。
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Demo</title>
</head>
<body>
    <a href="http://jquery.com/">jQuery</a>
    <script src="jquery.js"></script>
    <script>
    // Your code goes here
    </script>
</body>
</html>
The src attribute in the <script> element must point to a copy of jQuery. Download a copy of jQuery from the Downloading jQuery page and store the jquery.js file in the same directory as your HTML file.
在<script>中的src屬性必須指向至jQuery的檔案。下載完jQuery的檔案後,須把jquery.js這個檔案,儲存在與HTML檔案相同的目錄之下。


在Document載入完成時,才執行程式碼 (Launching Code on Document Ready)

To ensure that their code runs after the browser finishes loading the document, many JavaScript programmers wrap their code in an onload function:
為了確保程式碼在Browser完成載入時才執行,許多的JavaScript程式設計師會把他們的程式碼放在onload這個function中
window.onload = function() {
    alert( "welcome" );
}
Unfortunately, the code doesn't run until all images are finished downloading, including banner ads. To run code as soon as the document is ready to be manipulated, jQuery has a statement known as the ready event:
但是放在onload理面的程式碼並不會等所有的圖片完成下載後才執行。當你有需要在載入完成之後才執行的程式碼,可以利用jQuery提供的ready事件
$( document ).ready(function() {
    // Your code here
});
For example, inside the ready event, you can add a click handler to the link:
舉個例子,在ready事件中,你可以替超連結增加click的事件處理
$( document ).ready(function() {
    $( "a" ).click(function( event ) {
        alert( "Thanks for visiting!" );
    });
});
Save your HTML file and reload the test page in your browser. Clicking the link should now first display an alert pop-up, then continue with the default behavior of navigating to http://jquery.com.
現在儲存你的HTML檔並且在Browser中重新整理你的測試頁面。當你點擊網頁中的連結時,你會發現它會先彈出alert視窗,然後繼續執行Browser的預設動作連結至 http://jquery.com

For click and most other events, you can prevent the default behavior by calling event.preventDefault() in the event handler:
對於click和其他大多數的事件,你可以藉由在事件處理中呼叫event.preventDefault()來防止它執行預設動作
$( document ).ready(function() {
    $( "a" ).click(function( event ) {
        alert( "As you can see, the link no longer took you to jquery.com" );
        event.preventDefault();
    });
});

完整的範例 (Complete Example)

The following example illustrates the click handling code discussed above, embedded directly in the HTML <body>. Note that in practice, it is usually better to place your code in a separate JS file and load it on the page with a <script> element's src attribute.
下面的範例是上面所討論的完整程式碼,直接把click事件處理嵌入HTML的<body>中即可。
在實作的時候需注意:我們通常把JavaScript程式碼獨立在單獨的JS檔,並透過<script>的src屬性載入,可增加程式碼日後的維護性
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Demo</title>
</head>
<body>
    <a href="http://jquery.com/">jQuery</a>
    <script src="jquery.js"></script>
    <script>
    $( document ).ready(function() {
        $( "a" ).click(function( event ) {
            alert( "The link will no longer take you to jquery.com" );
            event.preventDefault();
        });
    });
    </script>
</body>
</html>

增加和移除HTML Class ( Adding and Removing an HTML Class )

Important: You must place the remaining jQuery examples inside the ready event so that your code executes when the document is ready to be worked on.
TIP : 當document完成載入後,你的程式碼就會被執行,所以你必須將你的jQuery範例放到ready中

Another common task is adding or removing a class.
另一個普通的目標是增加或移除Class
First, add some style information into the <head> of the document, like this:
首先,增加一些style設定到你的HTML檔的<head>中,如下:
<style>
a.test {
    font-weight: bold;
}
</style>
Next, add the addClass() call to the script:
接著,替你的元件呼叫addClass():
$( "a" ).addClass( "test" );
All a elements are now bold.
現在所有的超連結(a)元件就都會套用在第一步設定的style了
To remove an existing class, use removeClass():
而我們可以透過呼叫removeClass()來移除已設定Class的元件:
$( "a" ).removeClass( "test" );

特效處理 (Special Effects)

jQuery also provides some handy effects to help you make your web sites stand out. For example, if you create a click handler of:
jQuery也提供一些特效處理讓你的網站與別人不一樣。下面的例子是觸發超連結click事件的特效處理:
$( "a" ).click(function( event ){
    event.preventDefault();
    $( this ).hide( "slow" );
});
then the link slowly disappears when clicked.
當你點擊這個超連結的時候,你就會發現超連結緩慢的消失了。

Callback 與 函數 (Callbacks and Functions)
Unlike many other programming languages, JavaScript enables you to freely pass functions around to be executed at a later time. A callback is a function that is passed as an argument to another function and is executed after its parent function has completed. Callbacks are special because they patiently wait to execute until their parent finishes. Meanwhile, the browser can be executing other functions or doing all sorts of other work.
JavaScript不像許多其他程式語言,它允許你自由的傳遞函數以便在以後的時間被執行。callback可以將一個function當做參數傳遞到另一個function中執行,當父function執行完成後才會呼叫執行callback函數。callback特別的地方在於它會等待父function完成後才執行。在等待父function完成的同時,browser可以執行其他的function或作各種其他的工作。
To use callbacks, it is important to know how to pass them into their parent function.
使用callback時,重點在於知道如何將它們傳遞到它所屬的父function

沒有引數的Callback (Callback without Arguments)

If a callback has no arguments, you can pass it in like this:
如果callback沒有任何參數,那你可以像下面這樣傳遞:
$.get( "myhtmlpage.html", myCallBack );
When $.get finishes getting the page myhtmlpage.html, it executes the myCallBack function. Note that the second parameter here is simply the function name (but not as a string and without parentheses).
當get完成傳遞至myhtmlpage.html時,接著會執行myCallBack function
注意:第二個參數在這裡是簡單的funcation名稱 ( 但不是一個字串,且沒有攜帶任何參數 )

攜帶引數的Callback (Callback with Arguments)

Executing callbacks with arguments can be tricky.
攜帶引數執行的Callback可能會有點棘手
Wrong ( This code example will not work) :
錯誤的範例 ( 這個範例不會被正常執行 )
$.get( "myhtmlpage.html", myCallBack( param1, param2 ) );
The reason this fails is that the code executes myCallBack( param1, param2 ) immediately and then passes myCallBack's return value as the second parameter to $.get. We actually want to pass the function myCallBack, not myCallBack( param1, param2 )'s return value (which might or might not be a function). So, how to pass in myCallBack and include its arguments?
上述例子失敗的原因是因為程式碼會立即執行myCallBack( param1, param2 ),然後將myCallBack的回傳值代入$.get的第二個參數。我們實際上是想要傳遞myCallBack整個function,不是myCallBack的回傳值(回傳值可能是或可能不是一個function)。所以,要如何傳遞myCallBack與它的參數呢?

Right
正確的範例
To defer executing myCallBack with its parameters, you can use an anonymous function as a wrapper. Note the use of function() {. The anonymous function does exactly one thing: calls myCallBack, with the values of param1 and param2.
要延緩執行myCallBack與其參數,你可以將其包裝在匿名的function中。注意:匿名function中將會呼叫myCallBack並代入param1和param2的值
$.get( "myhtmlpage.html", function() {
    myCallBack( param1, param2 );
});
When $.get finishes getting the page myhtmlpage.html, it executes the anonymous function, which executes myCallBack( param1, param2 ).
當get完成傳遞至myhtmlpage.html時,將會執行這個匿名function,進而執行myCallBack( param1, param2 )


參考來源
  1. jQuery - 如何開始運作jQuery
    http://learn.jquery.com/about-jquery/how-jquery-works/
  2. This world My World - 引數?! 參數??!! 什麼鬼啊!!
    http://thisworldmyworld.blogspot.tw/2009/12/blog-post_08.html



沒有留言:

張貼留言