Must if addclass by addremove

时间:2017-06-19 14:03:20

标签: javascript jquery

How can I add / remove a class to an element when the URL?

I want to do with if

Example

if url

{ addclass('active'); //true

} else {

removeclass('active'); //false

}

var url = window.location.href;	

$('.info-project').find('a').each(function() {
  $(this).addClass('active', $(this).attr('href') == url);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="info-project">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Blog</a></li>
</ul>
</div>

1 个答案:

答案 0 :(得分:1)

试试这个:将代码放在$(function(){})中,以便加载DOM。把if else条件放在如下所示

$(function(){
var url = window.location.href;	

$('.info-project').find('a').each(function() {
  if($(this).attr('href') == url){
      $(this).addClass('active');
  } else {
          $(this).removeClass('active');
  }
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="info-project">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Blog</a></li>
</ul>
</div>