第二堂課開始講的是Jquery

雖說w3cSchool 內有介紹Jquery ,但實際還是因該道其官網去找才會是最新的

官網(http://jquery.com/)

到官網可看到幾個區塊

Jquery、UI、Mobile...等

但此次課程僅教到 Jquery 及 UI 

首先  要先來下載Jquery Library

並放入Js 目錄內

然後就可匯入前端程式參考如下:

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

之後便可如Js 一樣

<script type="text/javascript">

window.onload= function(){

    alert("show 訊息1");

}

 

window.onload= function(){

    alert("show 訊息2");

}

$(document).ready(function(){

     alert("show ready");

});

 

//more Jquery code

</script>

以上介紹window.onload;

window.onload 顧名思義 就是程式在onload時進入點

而這也只會呼叫一次且比較特別的地方是如果有一個以上也只會呼叫離結束區塊

最近的window.onload 跟一般程式是相反過來。

另一個則是 $(document).ready()    

這則是在Dom被load完時就會被呼叫;

所以以上 範例執行時 就會先顯示    "show ready"  ,在來就是離結束最近的 "show 訊息1"

可看看官網說明 :http://api.jquery.com/category/events/document-loading/

.onload(): Bind an event handler to the “load” JavaScript event.

.ready(): Specify a function to execute when the DOM is fully loaded.

.unload(): Bind an event handler to the “unload” JavaScript event.

來介紹一下Html生命週期

以Html5 為例: <head>  >>  <body> >> ready() >> load/onload >> pageShow >>PageHide >> unload

由以上可知 body 完後 就是  ready() 在來才 onload

 

PS: 在選擇器中$("")  不管是使用雙引號或單引號 都可以通,可方便做一些區別,而$號的表示也是有些不同轉換以防衝突(可以查一下)

$()  選擇器

1. 標籤選擇器 

Ex: $("a")  也就是指所有的 <a> 標簽(tag)

 

2.ID選擇器

Ex: $("#user1")     也就是指 <a  id="user1"> </a> 

 

3.Css 選擇器

Ex: $(".styleCss")  也是是 <a class="styleCss">  </a>

 

4.多組選擇器

Ex: $("p,#user1") 就是抓取<p> 標簽 及 ID="user1" 的資料

 

值得一題的是 $("#step1  #below2") 中間是用"空格"分開

這代表 step1  與 below2 之前有階層關係 , step1 階層必須大於below2

也就是ex:  <div id="step1">

                     <div id="below2"> </div>

                  </div>

 

5.多組

Ex: $("body *") 也就是指 body 內的所有元素

找個例子 : 

$("body *").each(function(Index){

      alert(Index + ":" + $(this).html());

});

<body>

    <div id="No1">第一個 </div>

    <div class="styleClass1"> 第一個class </div>

</body>

輸出結果: 0:第一個 1:第一個class       。

 

接下來介紹一下 addClass   ,顧名思義就是加入Class

ex:

.mydivclass{  color:yellow }

<div id="mydiv"> 測試中 </div>

以上如果使用 $("mydiv").addClass("mydivclass")  則"測試中"就會變為黃色

 

在來介紹一個特別的

toggleClass : Add or remove one or more classes from each element in the set of matched elements,

depending on either the class’s presence or the value of the switch argument.

這個屬性的好處是會幫你判斷 If else 條件  ($("div").toggleClass(".box")  也是是如果box存在就remove不存在就add       )

(toggleClass() uses the second parameter for determining whether the class should be added or removed.

If this parameter's value is true, then the class is added; if false, the class is removed. In essence, the statement:)

Ex :

$(document).ready(function(){

   $("<div id="box"> hello world!! </div>").appendTo("body").addClass("box"); //這意思指box這個div加入到body內並且在加入box的Class

  $("a").click(function(){

        $("div").toggleClass(".box");

    })

});

<body>

       <a href="#">  按我 </a>

</body>

 

 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 JoshS 的頭像
    JoshS

    JoshS的部落格

    JoshS 發表在 痞客邦 留言(0) 人氣()