提取css并与data-attribute匹配

时间:2017-09-23 20:05:24

标签: javascript jquery arrays

我有以下情况:

<body class="theme-blue nav-black">
  <a href="#" data-class="theme-blue">Blue theme </a>
  <a href="#" data-class="nav-black">Dark Nav</a>
  <a href="#" data-class="nav-white">Light Nav</a>
</body>

尝试编写一个脚本来匹配每个匹配的&#39;数据类的类和#39;添加一个类&#34;活跃&#34;到元素;

最好的办法是什么?

所以结果应该是这样的:

<body class="theme-blue nav-black">
  <a href="#" data-class="theme-blue" class="active">Blue theme </a>
  <a href="#" data-class="nav-black" class="active">Dark Nav</a>
  <a href="#" data-class="nav-white">Light Nav</a>
</body>

3 个答案:

答案 0 :(得分:2)

您可以循环每个a元素,然后使用hasClass()检查body是否具有相同的类,是否使用addClass()

$('a').each(function() {
  if ($('body').hasClass($(this).data('class'))) {
    $(this).addClass('active')
  }
})
.active {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body class="theme-blue nav-black">
  <a href="#" data-class="theme-blue">Blue theme </a>
  <a href="#" data-class="nav-black">Dark Nav</a>
  <a href="#" data-class="nav-white">Light Nav</a>
</body>

答案 1 :(得分:2)

var bodyClass=$("div").attr("class").split(" ");
$.map( bodyClass, function( val, i ) {
    $("a[data-class='"+val+"']").addClass('active');
});
.active{
 color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="theme-blue nav-black">
  <a href="#" data-class="theme-blue" >Blue theme </a>
  <a href="#" data-class="nav-black" >Dark Nav</a>
  <a href="#" data-class="nav-white">Light Nav</a>  
</div>

答案 2 :(得分:2)

使用jQuery

从正文中获取类,拆分,映射到数据属性字符串数组,然后加入。将类active添加到所有选定元素:

&#13;
&#13;
var classNames = $('body')
  .attr("class")
  .split(' ')
  .map(function(c) {
    return '[data-class="' +  c + '"]';
  })
  .join(',');
  
$(classNames).addClass('active');

console.log(classNames);
&#13;
.active {
  color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body class="theme-blue nav-black">
  <a href="#" data-class="theme-blue">Blue theme </a>
  <a href="#" data-class="nav-black">Dark Nav</a>
  <a href="#" data-class="nav-white">Light Nav</a>
</body>
&#13;
&#13;
&#13;

没有jQuery:

从正文中获取classList,并通过使用Array#slice将classList转换为数组,将类映射到数据属性字符串以及使用逗号连接,将其转换为字符串查询。 然后使用Document#querySelectorAll获取nodeList。使用NodeList#forEach迭代nodeList,并将active类添加到每个节点。

&#13;
&#13;
var classNames = [].slice.call(document.querySelector('body').classList, 0).map(function(c) {
  return '[data-class="' +  c + '"]';
}).join(',');

document.querySelectorAll(classNames).forEach(function(node) {
  node.classList.add('active');
});
&#13;
.active {
  color: red;
}
&#13;
<body class="theme-blue nav-black">
  <a href="#" data-class="theme-blue">Blue theme </a>
  <a href="#" data-class="nav-black">Dark Nav</a>
  <a href="#" data-class="nav-white">Light Nav</a>
</body>
&#13;
&#13;
&#13;