简体   繁体   English

jQuery:如果标记存在于self之上,则为标记添加样式

[英]jQuery: Add styling to tag if it exists above self

I want to .addClass("someClass" to <blockquote> if it has a <figure> with class hello above it, like this: 我想.addClass("someClass"<blockquote>如果它上面有一个带有类hello<figure> ,就像这样:

<figure class="hello"> world </figure>
<blockquote> Lorem </blockquote>

So, only if the <figure> tag is right above it, not if something is separating the tags like a div. 因此,只有当<figure>标记位于其上方时,才会将某些标记与div分开。

Is such thing possible? 这样的事可能吗?

Assuming this is to style the <blockquote> element when it is immediately preceded by a <figure> , then you can simply use CSS: 假设这是<blockquote>元素的样式,当它紧跟<figure>之前,那么你可以简单地使用CSS:

figure + blockquote {
    border-color: red; /* or whatever */
}

 section { border: 1px solid #000; margin: 0 0 1em 0; } blockquote { border: 1px solid #000; } figure + blockquote { border-color: #f00; } 
 <section> <figure>This is a figure</figure> <blockquote>And this is an immediately-following blockquote.</blockquote> </section> <section> <blockquote>This is a blockquote.</blockquote> <figure>And this is a figure following a blockquote</figure> </section> <section> <figure>Another figure</figure> <div>a div</div> <blockquote>And this is a blockquote.</blockquote> </section> 

References: 参考文献:

$('figure.hello + blockquote').addClass('someClass');

From jQuery's docs: 来自jQuery的文档:

Next Adjacent Selector (“prev + next”) 下一个相邻选择器(“prev + next”)

Selects all next elements matching "next" that are immediately preceded by a sibling "prev". 选择与“next”匹配的所有下一个元素,这些元素后面紧跟一个兄弟“prev”。

Can work from the known class ...is simplest 可以在已知类中工作......最简单

$('figure.hello').next('blockquote').addClass("someClass");

The way it works is if either selector isn't found, nothing happens and will only work for figure with folloing sibling being a blockuote 它的工作方式是,如果找不到任何一个选择器,没有任何反应,只会对于下面的兄弟是一个阻碍

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM