最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can I remove just the last added class from an element with jQuery - Stack Overflow

programmeradmin1浏览0评论

Hey guys, the question pretty much asks itself... however, for more clarity:

I have an element called "chuckPalahniuk" and it has classes named "choke", "fightclub" and "haunted".

How could I get it so when I click on the "chuckPalahniuk" element, it removes "haunted" first, then "fightclub" on the second click and "choke" on the third?

also: be aware that the class names are dynamically added.

Cheers. peeeps!

psy.example:

$('#chuckPalahniuk').click(function() {
  $(this).removeLastClassAdded(); //except this function doesn't exist...
});

Hey guys, the question pretty much asks itself... however, for more clarity:

I have an element called "chuckPalahniuk" and it has classes named "choke", "fightclub" and "haunted".

How could I get it so when I click on the "chuckPalahniuk" element, it removes "haunted" first, then "fightclub" on the second click and "choke" on the third?

also: be aware that the class names are dynamically added.

Cheers. peeeps!

psy.example:

$('#chuckPalahniuk').click(function() {
  $(this).removeLastClassAdded(); //except this function doesn't exist...
});
Share Improve this question edited Nov 11, 2010 at 15:05 Haim Evgi 126k46 gold badges222 silver badges226 bronze badges asked Nov 11, 2010 at 15:04 Barrie ReaderBarrie Reader 10.7k11 gold badges77 silver badges141 bronze badges 1
  • 1 get the class list by stackoverflow./questions/1227286/… and remove last entery – Haim Evgi Commented Nov 11, 2010 at 15:07
Add a ment  | 

3 Answers 3

Reset to default 4

just save in an array variable c every class you add c.push('yourclass'), then $(this).removeClass(c.pop());

http://www.devguru./technologies/ecmascript/quickref/pop.html

This will do it and will deal with leading and trailing whitespace, which a split()-based solution will not:

$('#chuckPalahniuk').click(function() {
    this.className = this.className.replace(/(^|\s+)[^\s]+(\s+)?$/, "");
});

Something like:

$('#chuckPalahniuk').click(function() {
    $(this).removeClass($(this).attr('class').split(/\s+/).pop());
});
发布评论

评论列表(0)

  1. 暂无评论