2012-04-12 42 views
0

假設我在文檔中有兩個p標籤。我想用jQuery調用兩種不同的效果,當onMouseOver事件發生時。是否有必要給這兩個p標籤給出ID。如果不給ID給這些標籤就不能實現它?在應用jquery函數時,Id是必需的嗎?

+5

見http://api.jquery.com/category/selectors/ – simon 2012-04-12 11:06:01

回答

5

你不給任何一個id,但它是唯一標識元素的最佳途徑。

可以代替idenfity按類:

$(".myClass") 

按屬性:

$("[src='image.jpg']") 

通過位置父:

$("p:eq(2)") 

選擇的完整列表是在documentation可用

+0

感謝回答!兩個'p'標籤都具有相同的類別。我想在段落中發生點擊事件時應用不同的功能。所以對於這個我想我們需要給這兩個段落ID? – niting112 2012-04-12 11:08:23

3

有幾種方法來選擇一個元素/元素:

$('.classname') 

$('#id') 

$('tagname') 

$('[attr="value"]') 

5
$('p:first'); // first p tag 
$('p:last'); // last p tag 
$('p').eq(1); // exactly the second p tag 
3

雖然jQuery的允許你寫的更快,更簡單的腳本,但不幸的是它讓你永遠不會了解真正的JavaScript。

$("*") //selects all elements. 

$(":animated") //selects all elements that are currently animated. 

$(":button") //selects all button elements and input elements with type="button". 

$(":odd") //selects even elements. 

$(":odd") //selects odd elements.$("p") selects all <p> elements. 

$("p.intro") //selects all <p> elements with class="intro". 

$("p#intro") //selects the first <p> elements with id="intro". 

$(this)  //Current HTML element 
$("p#intro:first") //The first <p> element with id="intro" 
$("p:eq(2)")  // The third <p> element in the DOM 
$(".intro")  //All elements with class="intro" 
$("#intro")  //The first element with id="intro" 
$("ul li:first") //The first <li> element of the first <ul> 
$("ul li:first-child") //The first <li> element of every <ul> 
$("[href]")  //All elements with an href attribute 
$("[href$='.jpg']")  //All elements with an href attribute that ends with ".jpg" 
$("[href='#']")  //All elements with an href value equal to "#" 
$("[href!='#']") //All elements with an href value NOT equal to "#" 
$("div#intro .head") //All elements with class="head" inside a <div> element with id="intro" 

的jQuery - 選擇元素cheat sheet

相關問題