jquery - 紧接子元素的 CSS 选择器
问题描述
两个简单的 HTML 示例:
<p>
<i>Some text</i>
</p>
<p>Here's a paragraph that has <i>some text</i>, and then some more</p>
使用 CSS 时,这<i>
两种情况下都会选择 's:
p > i {
border: 1px solid red;
}
>
目标<i>
中的每一个<p>
。
我正在寻找的是一种仅针对<i>
紧跟在 之后的 's 的方法<p>
,换句话说,<i>
在第一个示例中针对 the ,但在第二个示例中不针对。以一种+
选择相邻兄弟姐妹的方式,但对于相邻的孩子。这可能吗?
我查看了 jQuery 的only-child
选择器,但这也针对<i>
两个示例中的 's,因为文本(“here's a paragraph...”)不被视为子项。
解决方案
您不能使用 CSS 完成这项工作,但使用 javascript/jquery 您可以选择目标元素,如底部所示。
选择所有i
元素并用于.filter()
过滤所选元素。在过滤器回调中检查i
使用previousSibling
属性的先前文本。
$("p > i").filter(function(){
return this.previousSibling.nodeValue.trim() == "";
}).css("border", "1px solid red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
<i>Some text</i>
</p>
<p>Here's a paragraph that has <i>some text</i>, and then some more</p>
<p>
<i>Some text</i>
</p>
<p>text <i>some text</i>, text</p>
推荐阅读
- ios - 属性未在 SKScene 上初始化
- swift - 当我向下滚动表格视图时,隐藏单元格的复选标记消失了
- symfony - 树枝模板symfony 4中的重复表单行
- sql - 为什么 0 是 to_char(0,'B9999') 的例外?
- c++ - 弹出和推入堆栈
- javascript - 有没有办法在等待来自 API 的数据时不停止进度条?
- python - 我怎样才能提高我的 CNN 的准确度演变?
- ios - CIImage 显示 MTKView vs GLKView 性能
- laravel - 使用 Guzzle 在 Laravel 中使用外部 API 并保存到数据库中
- r - 更改校准图的颜色