Home > Article > Web Front-end > Introduction to the use of JQuery selector_jquery
jQuery element selectors and attribute selectors allow you to select HTML elements by tag name, attribute name, or content.
jQuery Element Selectors: jQuery uses CSS selectors to select HTML elements.
$("p") selects the
element.
$("p.intro") selects all
elements with class="intro".
$("p#demo") selects the first
element with id="demo".
jQuery Attribute Selector : jQuery uses an XPath expression to select elements with a given attribute.
$("[href]") selects all elements with href attribute.
$("[href='#']") selects all elements with an href value equal to "#".
$("[href!='#']") selects all elements with href value not equal to "#".
$("[href$='.jpg']") selects all elements whose href value ends with ".jpg".
Selector instance
语法 | 描述 |
---|---|
$(this) | 当前 HTML 元素 |
$("p") | 所有 元素 |
$("p.intro") | 所有 class="intro" 的 元素 |
$(".intro") | 所有 class="intro" 的元素 |
$("#intro") | id="intro" 的第一个元素 |
$("ul li:first") | 每个
|
$("[href$='.jpg']") | 所有带有以 ".jpg" 结尾的属性值的 href 属性 |
$("div#intro .head") | id="intro" 的 元素中的所有 class="head" 的元素 |
We will use the same three methods from the previous chapter to set up the content:
The four jQuery methods above: text(), html(), val() and attr() also have callback functions. The callback function takes two parameters: the index of the current element in the selected element list, and the original (old) value. Then return the string you wish to use as the function's new value.
$("#btn1").click(function(){ $("#test1").text(function(i,origText){ return "Old text: " + origText + " New text: Hello world ! (index: " + i + ")"; //return newText; }); });