Frage

I have a dynamically changing layout based on twitter bootstrap. It is a grid, with grid items that look something like this:

<div id="grid">
  <div class="row">
    <div class="span12 red"/>
  </div>
  <div class="row">
    <div class="span6 yellow"/>
    <div class="span6 green"/>
  </div>

</div>

Depending on user interaction, I need to be able to find items with a certain span class (i.e. span6) - and change it to a different span name (i.e. span4). I won't necessarily know what the span name that I'm changing is ahead of time, I just know it will start with "span" and that everything after that will need to be removed and appended with the new number. How do I do this in jQuery without clearing out the class names entirely?

In other words, I need to do some sort of find

([class*="span"]);
War es hilfreich?

Lösung

The best way to do this would be to iterate through each element and iterate through the class list of each element and check for "span", replacing the class if so. You can do that like so:

$('.row div').each(function () {
    var $object = $(this);
    $($(this).attr('class').split(' ')).each(function (i) {
        // If you want particular span classes to become new classes
        if(this.toString().indexOf("span3") >= 0) {
            $object.removeClass(this.toString());
            $object.addClass('special'); // New class to be added
        }
        // If you want all classes with "span" in them to become a new class
        else if (this.toString().indexOf("span") >= 0) {
            $object.removeClass(this.toString());
            $object.addClass('span1'); // New class to be added
        } 
    });
});

Demo here. This also includes an alternative method that strips the end of each class to get the same result

Andere Tipps

$('#grid .span6').toggleClass('span4 span6');

This will remove the class span6 and add the class span4 to all elements with the span6 class inside the grid

You can read more about the toggleClass method here

Update based on revised question:

I presume that the interaction you are mentioning will involved an element with one of the "span" classes and that the interaction is a jQuery event - i can't know since the question is too vague, but with these assumptions, the following should work:

function interactionHandler(e) {
 var newSpanName = '<put the span name you wish to switch to here>',
     spanName = this.className.replace(/(?:^|.*\s)(span\d)\(?:s.*|$)/,'');

 $('#grid .'+spanName).toggleClass(newSpanName + ' ' +spanName);
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top