为什么我的<a> tag selection isn&#39;t working?

时间:2016-11-12 21:58:33

标签: javascript jquery html

I have this code:

<div class="list-group" id="generalView">
    <a href="" id="today" onclick="displayData()" class="list-group-item" data-toggle="modal" data-target="#displayDiary">
        <h4 class="list-group-item-heading">Today's Diary</h4>
    </a>
    <a href="" class="list-group-item">
        <h4 class="list-group-item-heading">Last Week's Diaries</h4>
    </a>
    <a href="" class="list-group-item">
        <h4 class="list-group-item-heading">Last Month's Diaries</h4>
    </a>
</div>
$('#generalView > a').click(function(e) {
    e.preventDefault();
    $('#generalView > a').removeClass('active');
    $(this).addClass('active');
});

I want to add a class active when an <a> tag is clicked but my selection isn't working. Am I selecting wrong? I already tried to give a single class to every <a> element and then try to select that class but doesn't work as well. Why is this happening?

2 个答案:

答案 0 :(得分:0)

这是一个在每个标签上使用类的简单解决方案。希望它有所帮助!

&#13;
&#13;
$(document).ready(function(){
  $('#generalView > a').click(function() {
    $('.myClass').removeClass('active');
    $(this).addClass('active');
    return false;
});

});
&#13;
.active {
    color: red;
}
&#13;
<script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div class="list-group" id="generalView">
    <a href="" id="today" onclick="displayData()" class="list-group-item myClass" data-toggle="modal" data-target="#displayDiary">
        <h4 class="list-group-item-heading">Today's Diary</h4>
    </a>
    <a href="" class="list-group-item myClass">
        <h4 class="list-group-item-heading">Last Week's Diaries</h4>
    </a>
    <a href="" class="list-group-item myClass">
        <h4 class="list-group-item-heading">Last Month's Diaries</h4>
    </a>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

可以在没有js的情况下完成

根据您的情况考虑以下代码

&#13;
&#13;
a:active {
    color: orange;
}
&#13;
<script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div class="list-group" id="generalView">
    <a href="" id="today" class="list-group-item myClass" data-toggle="modal" data-target="#displayDiary">
        <h4 class="list-group-item-heading">Today's Diary</h4>
    </a>
    <a href="" class="list-group-item myClass">
        <h4 class="list-group-item-heading">Last Week's Diaries</h4>
    </a>
    <a href="" class="list-group-item myClass">
        <h4 class="list-group-item-heading">Last Month's Diaries</h4>
    </a>
</div>
&#13;
&#13;
&#13;