如何检查el是否具有与数组中的值匹配的类? [英] How to check if an el has a class that matches a value in array?

查看:135
本文介绍了如何检查el是否具有与数组中的值匹配的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组和一些path元素.我需要检查pathclass是否与数组中的值之一匹配,如果是,则向其中添加一个类fadeIn,我尝试了此操作:

I have an array and some path elements. I need to check if the class of a path matches one of the values in my array and if so add a class fadeIn to it, I tried this:

var nationList = ["usa", "france", "italy"];
var foundNations = $.unique(nationList.sort());
$("path").each(function() {
  for (var i = 0; i < foundNations.length; i++) {
    if ($(this).hasClass(foundNations[i])) {
      $(this).addClass("fadeIn");
    }
  }
});

.fadeIn {
  color: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<path class="spain">Spain</path>
<path class="italy">Italy</path>
<path class="germany">Germany</path>
<path class="usa">USA</path>

推荐答案

您需要使用文档就绪功能,其余的事情已经可以了.您只是错过了文档准备功能.这是运行代码:

You need to use document ready function rest of the things are already fine. You just missed document ready function. Here is the running code:

<style>
    .fadeIn {
        color: red;
    }
</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function (){
    var nationList = ["usa", "france", "italy"];
    var foundNations = $.unique(nationList.sort());
    $("path").each(function() {
      for (var i = 0; i < foundNations.length; i++) {
        if ($(this).hasClass(foundNations[i])) {
          $(this).addClass("fadeIn");
        }
      }
    });
});
</script>

<path class="spain">Spain</path>
<path class="italy">Italy</path>
<path class="germany">Germany</path>
<path class="usa">USA</path>

这篇关于如何检查el是否具有与数组中的值匹配的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆