如何检查el是否具有与数组中的值匹配的类?

时间:2018-06-06 10:20:15

标签: javascript jquery

我有一个数组和一些path元素。我需要检查一个class的{​​{1}}是否与我的数组中的某个值匹配,如果是这样,我会尝试添加一个类path

fadeIn
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;
}

2 个答案:

答案 0 :(得分:0)

你需要使用文件就绪功能休息的东西已经很好了。您刚刚错过了文档就绪功能。这是运行代码:

<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>

答案 1 :(得分:-1)

.includes函数可以检查数组值是否存在提供的值。如果存在则返回true ...所以你可以将它用于你的nationList数组..

var nationList = ["usa", "france", "italy"];

$("path").each(function(){
   if(nationList.includes($(this).attr('class'))) {
    $(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>