Frage

How can I use toggleCalss(), in a situation like this:

<div id="options"> 
  <span data-color="red">red</span> 
  <span data-color="green">green</span> 
  <span data-color="blue">blue</span> 
  <span data-color="black">black</span> 
</div>

<div id="target"> 
  <span class="icon home">target</span> 
</div>

$('#options').on('click', 'span', function () {
   var $iclass= $(this).data('color');
   $('#target').find('span').toggleClass($iclass)

});

In the example above existing class is not being replaced by the clicked one. It just keeps appending additional classes. Here is jsfiddle example as well: http://jsfiddle.net/5UbuD/3/

War es hilfreich?

Lösung

$('#options').on('click', 'span', function () {
    var r = $(this).siblings().map(function () {
        return this.getAttribute('data-color');
    }).get().join(' ');

    var t = this.getAttribute('data-color');

    $('#target').find('span').removeClass(r).toggleClass(t);
});

http://jsfiddle.net/z7hUM/

Andere Tipps

That is how toggleClass works.

One possible solution here is - I assume you have to preserve the classes home icon

var $tspan = $('#target').find('span'),
    tsclazz = $tspan.attr('class');
$('#options').on('click', 'span', function () {
    var $iclass = $(this).data('color');
    $('#target').find('span').attr('class', tsclazz + ' ' + $iclass)
});

Demo: Fiddle

You can check span class then remove it.

$('#options').on('click', 'span', function () {
    var $iclass = $(this).data('color');
    var elem = $('#target').find('span')
    if (elem.hasClass($iclass)) {
        elem.removeClass($iclass);
    } else {
        elem.removeClass().addClass("icon home " + $iclass)
    }
});

DEMO

http://jsfiddle.net/5UbuD/12/

$('#options').on('click', 'span', function () {
   var $iclass= $(this).data('color');
    var target = $('#target').find('span');
    // toggle class
    $iclass = target.hasClass($iclass) ? "" : $iclass;
   target.removeClass().addClass("icon home " +$iclass)

});

The best is maybe not to use toggleClass

$('#options').on('click', 'span', function () {
    var $iclass= $(this).data('color');
    $('#target').find('span').removeClass();
    $('#target').find('span').addClass($iclass);

});
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top