I have a document with a large number of pictures. The pictures are grouped in "piles" and each image will have the corresponding class "pile-x" where x is the pile #. So there may be 100 images grouped into five piles, and they woul开发者_如何转开发d have class names pile-1 ... pile-5. The user may drag and drop an image from one pile into another. When they do this, I'd like to remove the old pile-x class and add the new one. Is there a fast way to do this with jquery? One way would be to use regular expressions to match against $(this).attr('class'). Is there anything more efficient?
That would be your best way to do it if you must use the class attribute. If you're using an HTML5
doc type, you can use a data attribute. E.g.,
<img src="..." class="..." data-pile="5" />
Then in your script you can do this:
$('#the-image').data('pile'); // 5
And for setting the pile, just provide a new value. E.g.,
$('#the-image').data('pile', 2);
$('#the-image').data('pile'); // 2
You can try to do
$(this).removeClass('pile-1')
.removeClass('pile-2')
.removeClass('pile-3')
.removeClass('pile-4')
.removeClass('pile-5')
.addClass('pile-X');
In jQuery, you have to know the name of the class name you want to manipulate with .removeClass()
, .addClass()
or .toggleClass()
.
If there are no other classes on the object, you could just set the class to the new class name.
el.className = "pile-" + pileNum;
But, if there are other classes on the object and you want to use classes for this and you don't want to just use brute force to call removeClass on all possible pile class names, you will have to do like you suggested and parse the class to remove the name you want. Incidentally, this isn't that hard:
el.className = el.className.replace(/\bpile-\d+\b/gi, "") + " " + "pile-" + pileNum;
The jQuery way of doing this is to not use the class name for storing this information, but to use a data attribute on the object. Then, when you change piles, you can just directly set the data attribute on the object to the new pile number. If this were my code, that's probably how I would do it.
From http://api.jquery.com/removeClass/
To replace all existing classes with another class, we can use:
.attr('class', 'newClass')
So in your case this should do it:
.attr('class', "pile-"+x)
Where x is the new pile number. Also removeClass() alone will remove all clases. If you had an additional class that you wanted to keep you can add it later, like:
.attr('class', "pile-"+x).addClass('fixedclass')
精彩评论