我想在点击标题 p
和位于标题旁边的 div
中的其他 p
时更改 CSS 设置 p
HTML 结构
<div class="outerDiv">
<p id="headline">My headline</p>
<div id="listContainer">
<p>Text 1</p>
<p>Text 2</p>
<p>Text 3</p>
<p>Text 4</p>
</div>
</div>
当前解决方案
目前,我使用 jQuery 的 next()
、children()
和 addBack()
方法,但它只选择子项,并且不将其与标题 p
合并回来(我假设是因为 addBack()
会返回到 children
的倒数第二个 child ( ?))
$("p#headline").click(function() {
$(this).next().children().addBack().css({"background-color": "#000", "color": "#fff"})
})
如何在不编写第二行的情况下实现对 children
和标题 p
的选择? (jQuery 或 JavaScript)
编辑
一些 CSS 设置基于可能会更改的变量值
最佳答案
How can I achieve a selection of both the children and the headline p without writing a second line?
你可以这样做:
$(this).next().children().add(this).css(/*...*/);
addBack
不起作用,因为它添加回了下一个元素,而不是this
。
但我不会那样做。相反,我会这样做:
$(this).closest(".outerDiv").addClass("some-class-named-semantically");
...并有一个 CSS 规则,例如:
.some-class-named-semantically #headline,
.some-class-named-semantically #listContainer p {
background-color: #000;
color: #fff;
}
我不知道点击这个标题意味着什么,但是例如如果它选择了它,那么类名可能会被选择
。
重新编辑:
Some of the CSS settings are based on variables' values which may change
通常可以通过主题类来解决。但无论如何,您提出的主要问题已在本答案的开头得到解答。
关于javascript - 如何在一行中选择该元素和下一个元素的子元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56287357/