如何添加类到li元素使用jQuery?

时间:2018-11-17 07:04:47

标签: javascript jquery

我有这个HTML:

var hash = window.location.hash; // got e.g: #tab-cultura
$(".nav-tabs").find(hash).parent().addClass("active");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
so for that I am trying this Jquery but seems not working:(
<ul class="nav nav-tabs">
  <li class="tab-null"></li>
  <li><a href="#tab-cidadania" data-cat="cidadania" data-toggle="tab">Cidadania</a></li>
  <li><a href="#tab-cultura" data-cat="cultura" data-toggle="tab">Cultura</a></li>
  <li><a href="#tab-educacao" data-cat="educacao" data-toggle="tab">Educação</a></li>
  <li><a href="#tab-bem-estar-e-ambiente" data-cat="bem-estar-ambiente" data-toggle="tab">Bem-estar
            &amp; Ambiente</a></li>
  <li><a href="#tab-dinheiro" data-cat="dinheiro" data-toggle="tab">Dinheiro</a></li>
  <li><a href="#tab-ciencias-e-tecnologia" data-cat="ciencia" data-toggle="tab">Ciência
            e Tecnologia</a></li>
</ul>

现在,在页面重新加载时,我得到了这个字符串#tab-cultura

现在我想向名为active的元素li的{​​{1}}元素添加一个名为a的类

4 个答案:

答案 0 :(得分:3)

只需使用glDepthRange vec2 ndc_xy = -1.0 + 2.0 * gl_FragCoord.xy/u_resolution.xy;

[href=#tab-cultura]
var hash = "#tab-cultura";
$(".nav-tabs [href="+hash+"]").parent().addClass("active");
.active {
  background-color: yellow;
}

答案 1 :(得分:0)

通过选择器的方式

var hash = window.location.hash; // got e.g: #tab-cultura
$(".nav-tabs").find("[href='"+hash+"']").parent().addClass("active");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
so for that I am trying this Jquery but seems not working:(
<ul class="nav nav-tabs">
  <li class="tab-null"></li>
  <li><a href="#tab-cidadania" data-cat="cidadania" data-toggle="tab">Cidadania</a></li>
  <li><a href="#tab-cultura" data-cat="cultura" data-toggle="tab">Cultura</a></li>
  <li><a href="#tab-educacao" data-cat="educacao" data-toggle="tab">Educação</a></li>
  <li><a href="#tab-bem-estar-e-ambiente" data-cat="bem-estar-ambiente" data-toggle="tab">Bem-estar
            &amp; Ambiente</a></li>
  <li><a href="#tab-dinheiro" data-cat="dinheiro" data-toggle="tab">Dinheiro</a></li>
  <li><a href="#tab-ciencias-e-tecnologia" data-cat="ciencia" data-toggle="tab">Ciência
            e Tecnologia</a></li>
</ul>

答案 2 :(得分:-1)

从URL检查#查询字符串

var hash = window.location.hash;

在目标锂中添加活动班

$(".nav-tabs [href="+hash+"]").parent().addClass("active").siblings().removeClass("active");

答案 3 :(得分:-2)

$(".nav-tabs [href='#tab-cultura'").parent().addClass('active')