jQuery嵌套DOM选择器(jQuery nested DOM selector)

假设我有以下HTML元素:

<div id="id"> <div class="first"> <div class="second"></div> </div> </div>

我想知道为什么这不起作用在jQuery :

$("#id.first.second").click( // do some stuff ...

我通常使用类似以下的工作,但今天我只是发现上述示例不起作用。

// working example $("#id .second").click( // do some stuff ...

更新:我的问题是为什么没有空格它不工作? 谢谢!

Let say I have the following HTML elements:

<div id="id"> <div class="first"> <div class="second"></div> </div> </div>

I'm wondering why this doesn't work in jQuery:

$("#id.first.second").click( // do some stuff ...

I usually use something like the following which works fine, but today I just found out that the above example is not working.

// working example $("#id .second").click( // do some stuff ...

Update: My question is why it is not working without spaces? Thanks!

最满意答案

选择器#id.first.second表示“具有id值"id" “的元素,它具有first和second类”。

你的第二个选择器#id .second (带有#id .second之前的.second )意味着“一个id值为"id"元素,它有一个带有class second的后代元素”。 这是一个“后代选择器”。

所以如果你想指定三个层次中的每一个,你可以这样做:

$("#id .first .second").click(...

...这意味着“具有id值的元素"id"具有类的first一个后代元素,而first一个类具有second类的后代元素”。

或者,您可以这样做:

$("#id > .first > .second").click(...

...这意味着“一个id值为"id" “的元素,它具有一个直接的子元素,该元素first类,然后是一个带有second类的直接子元素,它是一个子选择器 (实际上是其中的两个)。

或者,当然,他们的一些组合。

The selector #id.first.second means "an element with the id value "id" which also has the classes first and second".

Your second selector #id .second (with the space before .second) means "an element with the id value "id" which has a descendant element with class second". It's a "descendant selector".

So if you want to specify each of the three levels, you'd do this:

$("#id .first .second").click(...

...which means "an element with the id value "id" which has a descendant element with the class first which, in turn, has a descendant element with class second".

Or alternately, you might do:

$("#id > .first > .second").click(...

...which means "an element with the id value "id" which has a direct child element with the class first which, in turn, has a direct child element with class second. It's a child selector (actually two of them).

Or, of course, some combination of them.

更多推荐