简体   繁体   中英

Click event on <a> element not firing

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>

It's possible you do not have the jQuery firing at the right time. I suggest wrapping it in a $(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 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM