简体   繁体   中英

Jquery switch class on click event

I have the folowing example:

<div class="filtrer">
    <a class="bold">Url 1</a>
    <a>Url 2</a>
</div>

First url is active, second is inactive, bold means is selected. I should be allowed to press only on Url 2, and as soon as i do that, the bold class shoud switch to the Url 2.

What i already tryed and did not work was this:

$('.filtrer a').filter(':not(.bold)').on('click', function(){
    var current = $('.filtrer a').filter(':not(.bold)');
    var standby = $('.filtrer a.bold');

    current.addClass('bold');
    standby.removeClass('bold');
})

Does anybody know why this is not working? Or have an optimized solution? Thanks

You are dealing with dynamic element selectors, so you need to use delegation based event handlers

var $as = $('.filter a');
$('.filter').on('click', 'a:not(.bold)', function () {
    var current = $as.filter(':not(.bold)');
    var standby = $as.filter('.bold');

    current.addClass('bold');
    standby.removeClass('bold');
})

Demo: Fiddle

It can be written as

var $as = $('.filter a');
$('.filter').on('click', 'a:not(.bold)', function () {
    $as.toggleClass('bold');
})

Demo: Fiddle

$('.filter').on('click','a:not(.bold)',function(){
  $(this).siblings().add(this).toggleClass('bold');
});

Or without jQuery:

<div class="filter">
  <input type="radio" name="url" id="url1"><label for="url1">url1</label>
  <input type="radio" name="url" id="url2"><label for="url2">url2</label>
</div>

.filter input[type=radio]{
  display:none;
}
.filter input[type=radio]:checked + label{
  font-weight:bold;
}

Example 1 Example 2

您拼错了“过滤器”,请在代码或HTML中对其进行更改。

$('.filtrer').on('click',' a:not(.bold)', function(){    
    $('.filtrer a.bold').removeClass('bold');;
    $(this).addClass('bold');    
})

Something like :

$('.filter a').click(function() {
    $('.filter a').removeClass('bold');
    $(this).addClass('bold');
});

?

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