jQuery

jQuery

基本概念

jQuery簡單的說是一些常用JavaScript的集合,讓我們可以直接利用別人已經寫好的JavaScript。採用jQuery還有另一個好處:很多跨瀏覽器相容的問題,在jQuery中已經提供解決方案。引用的方式有兩種,第一種是將js檔案下載下來,並在html的<head></head>中定義使用下載的js檔案。

<head>
<script src="jquery-3.1.1.min.js"></script>
</head>

第二種是使用Content Delivery Network (CDN),直接引用網路上的js檔案。網路上有很多CDN可以使用,如:google或微軟,如果使用google的CDN:

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>

如果使用微軟的CDN:

<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>
</head>

jQuery語法

jQuery的基本語法是: $(selector).action(),如果不熟悉selector的概念,請參考CSS。(jquery selector的語法,請詳參: jQuery Selectors)

$(this).hide() - hides the current element.
$("p").hide() - hides all <p> elements.
$(".test").hide() - hides all elements with class="test".
$("#test").hide() - hides the element with id="test".

以下就是一個使用了三種不同的selector的jQuery範例,定義當class="deleteBtn"的按鈕被按 ("click")時,被按的按鈕(this)的"data-id"的內容取代id="deleteID"的內容。

<script>
   $(function(){
      $(".deleteBtn").click(function(){
      $("#deleteID").val($(this).attr("data-id"));
     });
   });
</script>

與JavaScript相比:

  • 使用jQuery必須引用jQuery。
  • jQuery的語法較簡潔,例如,在JavaScript要使用getElementsByTagName、getElementsByClassName、getElementById去取得一個元素,而jQuery則直接利用selector去取得。
  • 在JavaScript是直接取代其屬性 (如innerHTML= "Hello World!"),而jQuery則是以參數的方式傳遞(如:.text("Hello World!"))。
  • jQuery可以將script都放在head,不像javascript必須將部份的script (如:getElementById)必須放在body中,可以讓script與html body清楚的切割。這也是使用jQuery的好處之一。

比較一下原本的寫法:

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>

</body>
</html>

同樣的效果,以jQuery寫。

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<script>
$(function(){
   $("#demo").text("Hello World!");
});
</script>
</head>
<body>

<p id="demo"></p>


</body>
</html>

下面的例子就是設定兩個按鈕,按"Hide",則隱藏所有"p"元素。按"Show",則顯示所有"p"元素。

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#hide").click(function(){
        $("p").hide();
    });
    $("#show").click(function(){
        $("p").show();
    });
});
</script>
</head>
<body>

<p>If you click on the "Hide" button, I will disappear.</p>

<button id="hide">Hide</button>
<button id="show">Show</button>

</body>
</html>

參考資料