Pregunta

I have a generic class which I want to add to a div on click. On the click it first will remove that class from any elements it has been added to, and then add it to the clicked element.

My problem is that on the second click it will not add the class.

You can see the result here - http://jsfiddle.net/47FPa/2/

.hilite{background-color:#d5d5d5; padding-bottom: 10px;border-radius:6px;margin-right:8px;}

<ul>
<li id="a"><a href="#a">Subject A</a></li>
<li id="b"><a href="#b">Subject B</a></li>
 <div class="a">
<a id="a"></a>
<h2>
    Subject A 
</h2>
    <p> Lorem ipsum eros nostrud inermis eam ei, ius ut noster ceteros, voluptua sensibus mnesarchum his et. Tamquam discere constituto his no. Viderer quaeque rationibus no nec, vel at esse accusamus, in has debet vituperata.</p>
</div>
<div class="b">
<a id="b"></a>
<h2>
    Subject B
</h2>
    <p>Vix ei amet fuisset, ad dolor nusquam accumsan pri, per erant interesset at. Ea aliquip elaboraret percipitur eos.</p>

<script> $('#a').click(function(){
$( 'div.hilite' ).removeClass();
$( 'div.a' ).addClass( 'hilite' );
});</script>

<script> $('#b').click(function(){
$( 'div.hilite' ).removeClass();
$( 'div.b' ).addClass( 'hilite' );
});</script>    
¿Fue útil?

Solución 3

I have updated the fiddle here Fiddle should work perfect.

<script> $('#a').click(function(){
    $( '.hilite' ).removeClass('hilite');
$( '#div_a' ).toggleClass('hilite');
});</script>

<script> $('#b').click(function(){
$( '.hilite' ).removeClass('hilite');
$( '#div_b' ).toggleClass('hilite');
});</script>

I have also just added id's to your div's (see fiddle).

Otros consejos

Remove <a id="a"></a> and <a id="b"></a>.

Because IDs must be unique. And I think these tags are of no use as click event is not attached to these.

Try:

$('#a').click(function(){
    $( '.hilite' ).removeClass('hilite');
    $( 'div.a' ).addClass( 'hilite' );
});

$('#b').click(function(){
    $( '.hilite' ).removeClass('hilite');
    $( 'div.b' ).addClass( 'hilite' );
});

Updated fiddle

Hope this helps..

Replace your script with this

<script> 
$(document).ready(function(){
    $('#a').click(function(){
        $( 'body' ).find('.hilite').removeClass('hilite');
        $( 'div.a' ).addClass( 'hilite' );
    });
    $('#b').click(function(){
        $( 'body' ).find('.hilite').removeClass('hilite');
        $( 'div.b' ).addClass( 'hilite' );
    });
})
</script>

Here is the JSfiddle

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top