在应用 jquery 函数时 Id 是必需的吗?

Is Id necessary in applying jquery functions?

本文关键字:Id 应用 jquery 函数      更新时间:2023-09-26

>假设我在文档中有两个p标签。我想在发生 onMouseOver 事件时使用 jQuery 调用两种不同的效果。是否有必要为这两个p标签提供 Id。如果不给这些标签提供 Id,就不能实现吗?

不必给任何东西一个id,但它是唯一标识元素的最佳方式。

您可以改为按类进行标识:

$(".myClass")

按属性:

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

按在父级中的位置:

$("p:eq(2)")

文档中提供了选择器的完整列表

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

有几种方法可以选择元素/元素:

$('.classname')
$('#id')
$('tagname')
$('[attr="value"]')

虽然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 – 选择元素备忘单