首页 > 解决方案 > 根据.filter返回结果改变多个div的css

问题描述

我正在尝试通过 Jquery 进行快速文本检查,文本是通过 API 引入的

jQuery(function($){
        $('cite.fn').filter(function () {
        return ["Van", "Motorbike", "Truck"].includes($(this).text());
        }).css('color', 'red');
});

HTML:

<cite class="fn"><?php echo $json['vehicle']; ?></cite> 

这很好用,如文本红色 - 如果响应是货车、卡车或摩托车

但是,需要发生的是,如果它是货车、卡车或摩托车,那么这个 div 应该显示

    <div class="citefailed">Sorry we can not offer <?php echo $json['vehicle']; ?> 
Schemes at this time - Then a load of buttons and stuff is inside this div too</div>

如果车辆类型是汽车,则此 div 显示

<div class="cited"> continue the form blah blah</div>

我试过的是

    jQuery(function($){
        $('cite.fn').filter(function () {
        return ["Van", "Motorbike", "Truck"].includes($(this).text());
        }).css('color', 'red');
        $(".cited").css({display: "none"});
        $(".citefailed").css({display: "block"});
   });

并且CSS有

.citefailed{display:none;}
.cited{display:block;}

但这似乎只是将 Display None 添加到 Cited div 并将显示块添加到 citefailed div,无论是汽车还是货车。

请参阅小提琴https://jsfiddle.net/hatorex1/1/

可以请一些建议

标签: jqueryfunctionfilter

解决方案


https://jsfiddle.net/akshayrathnavas/1yLv8r7k/16/

我做了一个改变,只用 CSS 和一个非常简单的 JavaScript 改变一个词。

jQuery(function($){
        $('cite.fn').filter(function () {
        return ["Van", "Motorbike", "Truck"].includes($(this).text());
        }).addClass('red');
});

和 CSS

cite.fn + .citefailed{display:none;}
cite.fn.red{ color: red;}
cite.fn.red + .citefailed{display:block;}
cite.fn.red + .citefailed + .cited {display:none;}

您也可以根据条件执行 $('.citefailed').show() 或 hide() 。


推荐阅读