如何使用jQuery最接近的方法添加应用CSS?

时间:2019-02-07 12:23:41

标签: javascript jquery html

$("p.ABC ").closest(".b .y").addClass("t");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="b">
  <h1 class="y">Hello</h1>
  <div class="a">
    <p class="ABC">A..........Z</p> //this could be present in some pages
  </div>
</div>
<div class="b">
  <h1 class="y">Hello</h1>
  <div class="a">
    <p class="BC">A..........Z</p> //this could be present in some pages
  </div>
</div>

我只想向第一个div的标签h1添加CSS属性。怎么做?

6 个答案:

答案 0 :(得分:2)

.closest()不适用于多级选择器。因此,closest(".b .y")将不匹配任何元素。

您必须在.find()元素上使用.closest()

console.log($("p.ABC ").closest(".b .y").length); // 0

$("p.ABC ").closest(".b").find(".y").addClass("t");
.t{
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="b">
  <h1 class="y">Hello</h1>
  <div class="a">
    <p class="ABC">A..........Z</p> //this could be present in some pages
  </div>
</div>
<div class="b">
  <h1 class="y">Hello</h1>
  <div class="a">
    <p class="BC">A..........Z</p> //this could be present in some pages
  </div>
</div>

不过,我认为最简单的方法是:

$(".b:eq(0) h1.y").addClass("t");

答案 1 :(得分:0)

$('。b h1:first')。addClass(“ t”);

答案 2 :(得分:0)

您还可以使用以下内容:

$("p.ABC ").closest(".a").prev('.y').addClass("t");
.t{
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="b">
  <h1 class="y">Hello</h1>
  <div class="a">
    <p class="ABC">A..........Z</p> //this could be present in some pages
  </div>
</div>
<div class="b">
  <h1 class="y">Hello</h1>
  <div class="a">
    <p class="BC">A..........Z</p> //this could be present in some pages
  </div>
</div>

此行首先获取类ABC的父级(最近),然后找到通过y方法放置在该父级之前的类prev,然后添加一个类t

答案 3 :(得分:0)

下面将仅在第一个匹配的div中突出显示标题

$("p.ABC")            // your starting selector
      .closest(".b")  // get the closest b div
      .first()        // only get the first of these
      .find('.y')     // find the title
      .addClass("t"); // add class to the first div's title only
.t {
  color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="b">
  <h1 class="y">Hello</h1>
  <div class="a">
    <p class="ABC">A..........Z</p> //this could be present in some pages
  </div>
</div>
<div class="b">
  <h1 class="y">Hello</h1>
  <div class="a">
    <p class="ABC">A..........Z</p> //this could be present in some pages
  </div>
</div>

答案 4 :(得分:0)

List<GPSData> gPSDatas = lstGPSData.Values.ToList(); 用于查找元素的父级。

选中这个。

closest()
$(".b h1:first").css("color","red");

答案 5 :(得分:0)

您可以通过两种方式实现这一目标:

1. $("p.ABC").closest("div.b").find("h1.y:first").addClass("t"); // you can add your css on t class.
2. $("p.ABC").closest("div.b").find("h1.y:first").css("color","green");

两个都可以正常工作。

相关问题