Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/415.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery-根据子容器的内容将类添加到父容器_Javascript_Jquery_Html - Fatal编程技术网

Javascript jQuery-根据子容器的内容将类添加到父容器

Javascript jQuery-根据子容器的内容将类添加到父容器,javascript,jquery,html,Javascript,Jquery,Html,我想根据子容器的内容向外部(父)容器添加一个类。我可以根据其内容将类添加到子容器中,但是如果我尝试将该类添加到父容器中,它会将其添加到页面上的所有容器中,而不仅仅是当前容器。有人能帮我更新代码,使它只将类添加到父容器中,而不是所有共享同一类的容器中吗?谢谢 jQuery: $('div.promotion-type').each(function () { var promotion = $(this).html(); console.log(promotion); if

我想根据子容器的内容向外部(父)容器添加一个类。我可以根据其内容将类添加到子容器中,但是如果我尝试将该类添加到父容器中,它会将其添加到页面上的所有容器中,而不仅仅是当前容器。有人能帮我更新代码,使它只将类添加到父容器中,而不是所有共享同一类的容器中吗?谢谢

jQuery:

$('div.promotion-type').each(function () {
    var promotion = $(this).html();
    console.log(promotion);
    if (promotion === "Special Event") {
        $("div.calendar-event").addClass("special-event"); // this is the only one with a class created for it so far
    } else if (promotion === "Daily Promotion") {
        $("div.calendar-event").addClass("daily-promotion");
    }
});
HTML:(许多容器中的1个)

  • 上午8时至下午6时。
    每日促销
  • 更改此选项:

    $(“div.calendar-event”).addClass(“特殊事件”)

    为此:

    $(this).parents(“div.calendar-event”).addClass(“特殊事件”)

    正如您已经知道的,使用选择器
    $(“div.calendar-event”)
    将选择
    日历事件的所有
    元素

    通过使用
    $(this).parents(“div.calendar-event”)
    ,您将查看起始
  • 元素的所有父元素,从最接近的父元素开始并向外推进。当它发现父元素是具有类
    日历事件的
    元素时,它将调用该父元素上的
    .addClass()

    而不是此-

    $("div.calendar-event", this).addClass("special-event");
    
    试试这个:

    this.find("div.calendar-event").addClass("special-event");
    
    • 使用text()而不是html()
    • 首先删除类
    • 使用$(此)
    代码:


    问题是您正在进行新的选择,而不是使用当前元素。试试看

    $(this).parent().parent().addClass(...);
    
    …或者可能

    $(this).parents('div.calendar-event').addClass(...);
    

    …取而代之。

    在容器元素上设置类的代码在哪里?@adeneo我已经更新了代码,以反映它被添加到父容器中,这会将它添加到页面上具有该类的所有容器中,而不是检查当前容器。只需使用
    $(this).closest(.calendar event)
    获取最接近的一个感谢您的帮助和对其工作原理的解释。
    $(this).parent().parent().addClass(...);
    
    $(this).parents('div.calendar-event').addClass(...);