jQuery
jQuery 是一个轻量的 JavaScript 库,
jQuery 包含了以下特性:
-
HTML/DOM manipulation
-
CSS manipulation
-
HTML event methods
-
Effects and animations
-
AJAX
-
Utilities
添加 JavaScript:
<head> <script src="jquery-1.12.4.min.js"></script> </head>
基本语法:
jQuery 是为了对 HTML 元素进行选择和操作而设计的,基本语法:
$(selector).action()
-
A $ sign to define/access jQuery
-
A (selector) to "query (or find)" HTML elements
-
A jQuery action() to be performed on the element(s)
jQuery 选择器
所有的 jQuery 选择器都是由 $() 开始,
元素选择
选择所有的 <p> 元素,
$("p")
id 选择
$("#test")
class 选择
$(".test")
还有以下这些例子:
$("*") // Selects all elements $(this) // Selects the current HTML element $("p.intro") // Selects all <p> elements with class="intro" $("p:first") // Selects the first <p> element $("ul li:first") // Selects the first <li> element of the first <ul> $("ul li:first-child") // Selects the first <li> element of every <ul> $("[href]") // Selects all elements with an href attribute $("a[target='_blank']") // Selects all <a> elements with a target attribute value equal to "_blank" $(":button") // Selects all <button> elements and <input> elements of type="button" $("tr:even") // Selects all even <tr> elements $("tr:odd") // Selects all odd <tr> elements
Get Content
jQuery methods for DOM manipulation are:
-
text() - Sets or returns the text content of selected elements
-
html() - Sets or returns the content of selected elements (including HTML markup)
-
val() - Sets or returns the value of form fields
Set Content
$("#btn1").click(function(){ $("#test1").text("Hello world!"); }); $("#btn2").click(function(){ $("#test2").html("<b>Hello world!</b>"); }); $("#btn3").click(function(){ $("#test3").val("Dolly Duck"); });
Add Elements
<script> $(document).ready(function(){ $("#btn1").click(function(){ $("p").append(" <b>Appended text</b>."); }); $("#btn2").click(function(){ $("ol").append("<li>Appended item</li>"); }); }); </script>
Remove Elements/Content
-
remove() - Removes the selected element (and its child elements)
-
empty() - Removes the child elements from the selected element