我有一个数组和一些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;
}
答案 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>