【问题标题】:I need to find all elements with the same class name and address the first one [closed]我需要找到具有相同类名的所有元素并解决第一个[关闭]
【发布时间】:2022-02-02 09:58:09
【问题描述】:

我有一个问题,我不确定如何解决它,或者是否有可能:在 WordPress 中,我构建了一个简单的事件日历。现在我想为某个日期的每个第一个事件设置样式。如何选择第一个事件?

https://arneteubel.com/kunden/rz-test/termine/

这是演示页面。每个事件的日期都是一个班级,所以我正在寻找的是这样的:

  1. 查找具有相同类的元素
  2. 选择第一个元素并应用样式

我无法按日期对我的活动进行分组……

现在这可能吗?也许用 PHP 或 jQuery?

谢谢!

【问题讨论】:

  • 不,抱歉,这不起作用,因为它会使所有背景都变黄。例如,我需要找到所有具有“Feb12023”类的 div,但只设置其中第一个的样式。但是“Feb12023”是动态的,因为它是事件的日期。
  • 对不起我之前的评论 :-) .. 从我的评论中删除您添加的任何内容,然后在下面查看我的答案

标签: php jquery css wordpress class


【解决方案1】:

我更喜欢使用 data- 属性而不是类

data-date="feb34454" 而不是class="feb34454"

查看下一个示例

$(document).ready(function(){
  $(".ct-nestable-shortcode").each(function(){
    let the_date = $(this).find("> div").data('date');
    $("[data-date='"+the_date+"']:first").css("background" , "yellow");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="ct-nestable-shortcode">
  <div data-date="feb34454">feb34454</div>
</div>
<div class="ct-nestable-shortcode">
  <div data-date="feb34454">feb34454</div>
</div>
<div class="ct-nestable-shortcode">
  <div data-date="feb34454">feb34454</div>
</div>

注意: 不要忘记包含 jquery

【讨论】:

    【解决方案2】:

    如果可能的话,你应该使用 CSS 作为样式。

    这是从this answer盗来的 CSS 解决方案:

     /* 
     * Select all .red children of .home, including the first one,
     * and give them a border.
     */
    .home > .red {
        border: 1px solid red;
    }
    

    ...然后“撤消”具有类在第一个之后的元素的样式,在覆盖规则中使用通用同级组合符 ~:

    /* 
     * Select all but the first .red child of .home,
     * and remove the border from the previous rule.
     */
    .home > .red ~ .red {
        border: none;
    }
    

    【讨论】:

    • 谢谢@Brian Danowski。这不起作用,因为我的班级名称是动态的,具体取决于事件的日期。这就是让它变得棘手的原因。
    猜你喜欢
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    • 2018-01-15
    • 1970-01-01
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多