jquery选择器 css_如何使用jQuery选择器和CSS选择器,以及它们如何工作的基础

jquery选择器 css

by Rasheed Bustamam

通过拉希德·布斯塔曼(Rasheed Bustamam)

如何使用jQuery选择器和CSS选择器,以及它们如何工作的基础 (How to use jQuery Selectors and CSS Selectors, and the basics of how they work)

The other day, I was interviewing someone who had finished the front-end certification of freeCodeCamp. He had also graduated from a rather prestigious bootcamp, where attendees coded from 8am to 8pm for six weeks straight. Yikes!

前几天,我在采访一个完成了freeCodeCamp前端认证的人。 他还从一个颇负盛名的训练营毕业,在那里,与会者从上午8点到晚上8点连续进行了六个星期的编码。 kes!

His programming ability was great, but I was surprised to see that his knowledge in CSS was lacking. And by lacking, I mean he didn’t know how to select a class to apply a style. This doesn’t necessarily reflect negatively on him. If anything, it highlights how a lot of programmers view CSS.

他的编程能力很强,但是我很惊讶地发现他缺乏CSS知识。 由于缺乏,我的意思是他不知道如何选择一个班级来应用一种风格。 这并不一定会对他产生负面影响。 如果有的话,它强调了很多程序员如何看待CSS。

Many people think learning CSS is unimportant, since designers will usually be able to implement the CSS for you. While this is true, there are many times that you (as the programmer) will need to know some basic CSS in order to select an element and tell it to do something when something else happens.

许多人认为学习CSS并不重要,因为设计人员通常可以为您实现CSS。 虽然这是事实,但很多时候(作为程序员)您需要了解一些基本CSS,才能选择一个元素并告诉它在发生其他事情时执行某些操作。

For example, Green Sock Animation Platform (GSAP) is probably too program-y to be designer-centric. It requires a developer with a knowledge of CSS as well as programming.

例如, Green Sock动画平台(GSAP)可能过于程序化而无法以设计师为中心。 它需要具有CSS和编程知识的开发人员。

I’m not saying that every developer needs to be a CSS master. But I think if you’re going to call yourself a full-stack developer, you should know the basics of CSS. And the basics start with the selector.

我并不是说每个开发人员都必须是CSS大师。 但是我认为,如果您要称自己为全栈开发人员,则应该了解CSS的基础知识。 并且基础从选择器开始。

Disclaimer: jQuery selectors aren’t actually unique to jQuery — they’re actually CSS selectors. However, if you’re anything like me, you learned jQuery before you properly learned CSS, and therefore automatically associated selectors with jQuery. Though this article is about CSS selectors, it will help you if you need some clarifications on jQuery selectors as well.

免责声明:jQuery选择器实际上并不是jQuery独有的-它们实际上是CSS选择器。 但是,如果您像我一样,则在适当学习CSS之前先学习了jQuery,因此自动将选择器与jQuery关联。 尽管本文是关于CSS选择器的,但是如果您需要对jQuery选择器进行一些说明,它也会为您提供帮助。

CSS选择器 (The CSS Selector)

I always find it helpful to play with code, so here’s a simple CodePen for playing with basic selectors.

我总是发现使用代码很有帮助,因此这里有一个简单的CodePen,用于使用基本选择器。

In HTML, there are three ways to label or categorize elements. The first way is the broadest: by tag name. For example, you can select all divs on your page by using the simple selector div. Hey, that was easy!

在HTML中,可以通过三种方式对元素进行标签或分类。 第一种方法是最广泛的:按标签名称。 例如,你可以选择所有 div通过使用简单的选择你的网页在S div 。 嘿,那很容易!

The second way is probably the one you’ll use the most: the class attribute. You can select by class by using a dot (.) , so in the example above, to select the all elements with class section I use .section as a selector.

第二种方法可能是您最常使用的一种方法: class属性。 您可以使用点( . )按类进行选择,因此在上面的示例中,选择全部 具有类section元素我使用.section作为选择器。

The third way is often overused, but still useful, and that’s the id attribute. IDs should identify your elements, just as your SSN (in the US) might identify you as a person. That means that IDs should be unique across the entire page. To select an element with a specific ID, you use the hashtag (#), or octothorpe as I like to call it. To select the element with the ID of other I use #other.

第三种方法经常被过度使用,但仍然有用,那就是id属性。 ID应该标识您的元素,就像您的SSN(在美国)可能标识您是一个人一样。 这意味着ID在整个页面上应该是唯一的。 要选择具有特定ID的元素,请使用井号 ( # ),或者按我喜欢的名称使用octothorpe 。 要选择other ID的元素,请使用#other

These are the most basic selectors. To recap:

这些是最基本的选择器。 回顾一下:

  • select by tag name (no prefix)

    按标签名称选择(无前缀)
  • select by class name (prefix of .)

    按类别名称选择(。的前缀) .

  • select by ID (prefix of #)

    按ID选择( #前缀)

These three selectors alone will allow you to select almost anything on your webpage.

仅这三个选择器就可以让您选择网页上的几乎所有内容。

测验1 (Quiz 1)

  1. How would you select all the paragraph tags on the page? (hint: paragraph tags are p)

    您如何选择页面上的所有段落标签? (提示:段落标记为p )

  2. How would you select all items with class of button-text?

    您将如何选择所有带有button-text类的项目?

  3. How would you select the element with ID of form-userinput?

    您将如何选择ID为form-userinput的元素?

Feel free to share your answers in the comments!

随时在评论中分享您的答案!

所有ID是否都必须唯一? (Do all IDs need to be unique?)

This is a small digression that I feel is very important. But if you’re only here to learn how to use selectors, feel free to skip to the next section

我觉得这是一个很小的题外话,非常重要。 但是,如果您只是在这里学习如何使用选择器,请随时跳到下一部分

With a name like ID, you’d assume that every HTML ID must be unique or your HTML document will not work. After all, trying to have two const variables will make many editors yell at you, so wouldn’t HTML yell too?

使用ID之类的名称,您将假定每个HTML ID 必须是唯一的,否则HTML文档将无法工作。 毕竟,尝试使用两个const变量会使许多编辑器大吼大叫,所以HTML也不会大喊大叫吗?

The problem is, HTML will not yell at you. In fact, no one will even tell you anything is wrong. You may find a bug that stems from a non-unique ID. But you will drive yourself crazy trying to figure out the root cause of the bug, because it is a very subtle failure.

问题是,HTML 不会对您大吼大叫。 实际上,没有人会告诉你任何错误。 您可能会发现源自非唯一ID的错误。 但是您会发疯,试图找出错误的根本原因,因为这是非常微妙的失败。

The example above demonstrates why having duplicate IDs might cause an issue on your webpage. First, there are actually two divs with the ID other. If you comment the styles for #other, you’ll see that both items actually get styled. This might make you think, “well hey, I can use IDs and classnames interchangeably!”

上面的示例演示了为什么拥有重复的ID可能会导致网页出现问题。 首先,实际上有两个div ,其ID为other 。 如果您注释#other的样式,则会看到两个项目实际上#other样式化。 这可能使您认为:“嘿,我可以互换使用ID和类名!”

Not so fast. If you look in the JavaScript panel, you’ll see that I selected particular items based on their element label: tag name, class name, or ID. You’ll notice that document.getElementsByTagName and document.getElementsByClassName return a collection of all matching HTML elements. document.getElementById returns only the first HTML element it can find with the matching ID. You can verify this by uncommenting the getVanillaSelectors function and checking the console.

没那么快。 如果您在JavaScript面板中查看,将会看到我根据元素标签:标签名称,类名称或ID选择了特定项目。 您会注意到document.getElementsByTagNamedocument.getElementsByClassName返回所有匹配HTML元素的集合。 document.getElementById仅返回它可以找到的具有匹配ID的第一个HTML元素。 您可以通过取消注释getVanillaSelectors函数并检查控制台来验证这一点。

To further complicate things, if you use JavaScript’s querySelectorAll method (which takes in a CSS selector as input), you get a totally different result.

更复杂的是,如果使用JavaScript的querySelectorAll方法(将CSS选择器作为输入),则会得到完全不同的结果。

And just to mess with you, jQuery does something different despite having a similar syntax to querySelectorAll.

只是让您感到querySelectorAll尽管jQuery的语法与querySelectorAll类似,但jQuery却做了一些不同的事情。

I have no explanation for the different behavior. However, I can tell you how to avoid it. Here are my rules:

对于这种不同的行为,我没有任何解释。 但是,我可以告诉您如何避免这种情况。 这是我的规则:

  1. Never use IDs. Use class attributes instead.

    切勿使用ID。 请改用class属性。

  2. If I need to use an ID, name-space it such that it will be unique even if a similar item exists on the page; for example menu-item-01

    如果我需要使用ID,请对其进行命名空间,以便即使页面上存在类似的项目,该ID也将是唯一的; 例如menu-item-01

Sometimes forms, and their input fields, may need to have IDs. In that case, you can follow rule number 2. Here’s how I would namespace a form for user-signup:

有时,表单及其输入字段可能需要具有ID。 在这种情况下,您可以遵循规则2。这是我为用户注册表单命名空间的方式:

<form id="user-signup">  <input id="user-signup-userid" label="user id" />  <input id="user-signup-password" label="password" /></form>

That way, if I have two forms on the same page (let’s say user-signup and user-signin), they are guaranteed to have unique IDs. Even if the userID fields are similar between the forms.

这样,如果我在同一页面上有两个表单(假设为user-signupuser-signin ),则可以确保它们具有唯一的ID。 即使表单之间的userID字段相似。

组合选择器 (Combining Selectors)

Sometimes a single selector just won’t cut it. Sometimes, you need to get every div that has a class name of section . Other times, you need every element with a class name of section that is a child element to a div with ID user-signup . There are many possible other selector combinations.

有时,一个选择器不会削减它。 有时,您需要获取每个类的名称为section div 。 其他时候,你需要的类名的每个元素section是一个子元素的div ID为user-signup 。 有许多其他选择器组合。

In this section, you will learn three ways of combining selectors, and I am confident that these will suit 90% of your needs. If you find that more than 11% of your needs are unfulfilled, come complain to me and I’ll edit that to say 89% of your needs :).

在本部分中,您将学习三种组合选择器的方法,我相信这些方法将满足您90%的需求。 如果您发现超过11%的需求无法满足,请向我投诉,我将其编辑为89%的需求:)。

As before, let’s start with a CodePen:

和以前一样,让我们​​从CodePen开始:

组合单个元素的选择器 (Combining selectors for a single element)

OK, first let’s cover combining selectors for a single element. This means selecting the element that has tag name of x, AND class name of y, AND ID of z. Of course, you don’t need all three, but you can combine all three.

好的,首先让我们介绍一下为单个元素组合选择器的过程。 这意味着选择标签名称为x ,类名称为y ,AND ID为z的元素。 当然,您不需要全部三个,但是您可以将所有三个结合起来。

Let’s say we want to select all divs with class of item. To do that, we combine the two: div.item. It goes from most general to most specific from left to right. That selects all div tags that ALSO have the class name of item. It’s important to note that there is no space between div and .item. Adding a space changes the selector completely, as I will go over in the next section.

假设我们要选择所有class为item div 。 为此,我们将两者结合: div.item 。 从左到右从最一般到最具体。 选择所有也具有item的类名的div标签。 重要的是要注意div.item之间没有空格。 添加空格会完全更改选择器,因为我将在下一部分中进行介绍。

If you uncomment the corresponding CSS, you’ll see that the section with the class name of item did not turn red. That’s because it’s not a div tag.

如果取消注释相应CSS,您将看到具有item的类名称的section没有变成红色。 那是因为它不是div标签。

You can do this same pattern with class names and IDs. But if you have an element’s ID, you may as well just use the ID. There’s no reason to select an ID with a specific class name, because if you followed the ID rules above, you only have one item with that ID anyway.

您可以使用类名和ID执行相同的模式。 但是,如果您具有元素的ID,则最好也使用ID。 没有理由选择具有特定类名称的ID,因为如果您遵循上述ID规则,则无论如何您只有一个具有该ID的项目。

But, just for parity, here’s an example of selecting the div with class of item and ID of other: div.item#other. Again, going from left to right, it goes most general to more specific.

但是,仅出于奇偶校验,这是一个选择带有item类和id为otherdiv的示例: div.item#other 。 同样,从左到右,它从最一般到更具体。

Most likely you’ll use this syntax to select an element that has multiple classes. To do this, just separate all the classes with periods. To select all elements that have BOTH classes item and section, you’d use .item.section. The order doesn’t matter when you’re doing it this way, so .section.item will work too.

您很有可能会使用此语法来选择具有多个类的元素。 为此,只需将所有类与句点分开即可。 要选择有两个类的所有元素itemsection ,你会使用.item.section 。 这样执行的顺序并不重要,因此.section.item也将起作用。

This one trick will allow you to be more specific in your selectors.

这一技巧将使您在选择器中更具体。

“子”选择器 (The “child” selector)

The second way you can combine selectors is by using the “child” selector, as I like to call it. There’s two ways of doing this, so I’ll start with the most general.

组合选择器的第二种方法是使用“子”选择器,就像我喜欢的那样。 有两种方法可以做到这一点,所以我将从最普通的方法开始。

First, you can select any child of a certain element by adding a space. For example, to select all child items of the #other element, it’d be #other .item. Notice the space between the selectors.

首先,您可以通过添加空格来选择某个元素的任何子元素。 例如,要选择#other元素的所有子item ,应为#other .item 。 注意选择器之间的空间。

Second, you can select immediate children of a certain element by using the &gt;. An “immediate child” of an element is one that is only one level deep. In the example, there are two .item elements contained in the #other element, but one of the .item elements is wrapped up in a .wrapper element, so that one is not an immediate child.

其次,您可以使用& gt;选择特定元素的直接子代。 元素的“直接子级”是仅深一层的元素。 在这个例子中,有T个wo .i包含在T TEM元件he #ot她的元素,但T的一个he .i TEM元件被包裹起来a .wrap每个元素,使一个不是立即的孩子。

To give you a visual, if you collapse everything underneath the #other element, you’d see this:

为了给您一个视觉效果,如果将所有内容折叠在#other元素下,则会看到以下内容:

Those two are the only direct children of the #other element. To select only the direct child .item of #other, you’d use #other > .item, which would select the direct child, but not the one underneath .wrapper. Nifty, huh?

这两个是#other元素的唯一直接子代 。 只选择直接子.item#other ,你会使用#other > .i TEM,这将选择直接孩子,B UT不是一个undernea th .wrap每。 太漂亮了吧?

测验2 (Quiz 2)

  1. How would you select all the paragraph tags that belong to section elements? (hint: paragraph tags are p)

    您将如何选择属于section元素的所有段落标签? (提示:段落标记为p )

  2. How would you select all items with class of button-text, that are descendants to items with class of button?

    你会如何选择带班的所有项目button-text ,是后人与类的物品button

  3. How would you select the element with class of form-input that is a direct child of form elements?

    您将如何选择具有form-input类的元素,它是form元素的直接子元素?

  4. Bonus question: explain what this selector selects: header.title > form.user-signup button.button-danger

    额外的问题 :解释此选择器选择的内容: header.title > form.user-signup button.button-dan ger

As before, feel free to share your answers in the comments!

和以前一样,请随时在评论中分享您的答案!

全部放在一起-从字面上看 (Putting it all together — literally)

You can combine combined selectors. Really. The bonus question above shows an example of it, but I’ve added some combinations at the end of the example codepen.

您可以组合组合的选择器。 真。 上面的奖励问题显示了一个示例,但我在示例代码笔的末尾添加了一些组合。

For example, you can choose all .items that are children of divs with class of parent-item by using div.parent-item .item. Whoa!

例如,您可以使用div.parent-item .item来选择所有.item divparent-itemdiv.parent-item .item ,它们是divparent-item ,并且具有parent-item类。 哇!

You can choose direct descendants as well. For example, to select all divs with class of item that are direct descendants to divs with class of parent-item: div.parent-item > div.item.

您也可以选择直接后代。 例如,要选择所有item类别为div的直接divparent-item类别为div.parent-item > div.i tem的所有div

And finally, just to mess with you, you can walk down the entire DOM tree: div.parent-item .coolest-item .item. item class that is child to coolest-item class that is child to div with class of parent-item.

最后,为了使您满意,您可以沿着整个DOM树div.parent-item .coolest-item .itemdiv.parent-item .coolest-item .itemitem类,它是孩子coolest-item类,它是孩子div与类的parent-item

Note that it’s generally not a good idea to go beyond two or three levels of depth when nesting selectors. Then you get into weird realms of specificity that you can solve more effectively by naming your CSS classes better. But that’s out of the scope of this article. If you want to know more, let me know and I’ll write about it.

请注意,嵌套选择器时,通常不要超过两个或三个深度级别。 然后,您进入了一些特殊的怪异领域,可以通过更好地命名CSS类来更有效地解决这些问题。 但是,这超出了本文的范围。 如果您想了解更多,请告诉我,我会写信。

奖励:使用Chrome DevTools获取选择器 (Bonus: Using Chrome DevTools to get a selector)

You can use Chrome DevTools to get the selector of any element you can select on the DOM. Here’s how:

您可以使用Chrome DevTools获取可以在DOM上选择的任何元素的选择器。 这是如何做:

  1. Open Chrome DevTools. Since you’re selecting an element, go ahead and right click the element you want to select and click on “Inspect”:

    打开Chrome DevTools。 由于您正在选择元素,因此继续并右键单击要选择的元素,然后单击“检查”:

2. Right click the DOM element you want to select and hover over “Copy,” then click on “Copy Selector:”

2.右键单击要选择的DOM元素,然后将鼠标悬停在“复制”上,然后单击“复制选择器:”

3. That’s it! The selector I copied, by the way, is #editor_93 > section > div.section-content > div:nth-child(3) > p.graf.graf — p.graf-after — figure.graf — trailing.is-selected. You can copy the selector into document.querySelector or jQuery and get the element.

3.就这样! 顺便说一下,我复制的选择器是#editor_93 > section > div.section-content > div:nth-child(3) > p.graf.graf — p.graf-after — figure.graf — trailing .is-已选择。 您可以将选择器复制lector into document.q uerySelector或jQuery中并获取元素。

Hopefully this writeup was helpful! If you enjoyed it, please give me some claps so more people see it. Thanks!

希望本文对您有所帮助! 如果您喜欢它,请给我一些鼓掌,以便更多的人看到它。 谢谢!

翻译自: https://www.freecodecamp.org/news/back-to-basics-demystifying-css-and-jquery-selectors-12d75946b8b7/

jquery选择器 css

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值