My HTML is structured as below. I would like to give the clicked <a>
element the class "active".
Although the debugger stops on the click()
line, the code within the function is not being triggered.
$('#dropdownRow > div > a').on('click', function(e) {
$('#dropdownRow a.active').removeClass('active');
var $this = $(this);
if (!$this.hasClass('active')) {
$this.addClass('active');
}
e.preventDefault();
})
.active { color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row" id="dropdownRow">
<div class="col-xs-3">
<a href="/xxx/">XXX</a>
</div>
<div class="col-xs-3">
<a href="/yyy/">YYY</a>
</div>
<div class="col-xs-3">
<a href="/zzz/">ZZZ</a>
</div>
</div>
答案 0 :(得分:3)
您可能没有在正确的时间点击jQuery。我建议将它包装在$(document).ready
中https://learn.jquery.com/using-jquery-core/document-ready/
$( document ).ready(function() {
// Add your code
$('#dropdownRow > div > a').on('click', function(e) {
$('#dropdownRow a.active').removeClass('active');
var $this = $(this);
if (!$this.hasClass('active')) {
$this.addClass('active');
}
e.preventDefault();
});
// End code
});