本文實例講述了jQuery選擇器用法。分享給大家供大家參考,具體如下:
jQuery 使用兩種方式來選擇 html 的 element,第一種使用CSS和Xpath選擇器聯合起來形成一個字符串來傳送到jQuery的構造器(如:$("div > ul a"));第二種是用jQuery對象的幾個methods(方法)。這兩種方式還可以聯合起來混合使用。
使用 CSS 和 XPath 選擇器選擇的方法有許多種用法,關于詳細的 CSS 選擇器可參考本站相關文章。
首先來看通過元素的 ID 取得元素:$( "#id" ),在名字前面增加 # 表示這是一個 id,注意引號不要丟掉。
在頁面中增加一個 id 為 msg 的 span 元素,將 helloworld 顯示在 span 元素中,可以如下實現:
<html><head> <title>Hello</title> <script src="jquery-1.2.5.js" type="text/javascript"></script> <script type="text/javascript"> $( function() { $("#msg").html("Hello, world."); } ); </script> </head><body> <span id="msg"/></body></html>
注意:#id 需要用引號引起來,有參數的 html 函數用來為元素的 innerHTML 賦值。
下一個例子:
比如我們有一個 list ,它的 ID 是 orderedlist,那么取得這個 list 的引用的 jQuery 就是 $( "#orderedlist" ),為它增加一個值為 red 的 class 屬性 $("#orderedlist").addClass("red"),addClass 函數用來為元素增加 CSS 設置。取得 list 中的最后一個 li 的引用,$( "#orderedlist li:last" )。
下面的例子將最后一個 li 的內容更改為 hello, world.
<html><head> <title>Hello</title> <script src="jquery-1.2.5.js" type="text/javascript"></script> <script type="text/javascript"> $( function() { alert("wait"); $( "#orderedlist li:last" ).html("hello, world."); } ); </script></head><body> <ol id="orderedlist"> <li>First element</li> <li>Second element</li> <li>Third element</li> </ol></body></html>
希望本文所述對大家jQuery程序設計有所幫助。
新聞熱點
疑難解答