admin管理员组

文章数量:1323714

​<button id="test" class="example whatever">Show classes</button>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

$('button').click(function(){
  var classes = $(this).attr('class');
  alert(classes);
});​

The above code returns the content of the class attribute. How can I get it to return the classes formatted?

For instance, in this case, I want the variable classes to have a value of .example.whatever instead of example whatever.

I've searched and the only solution that seemed to be provided is the code I demonstrated above.

​<button id="test" class="example whatever">Show classes</button>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

$('button').click(function(){
  var classes = $(this).attr('class');
  alert(classes);
});​

The above code returns the content of the class attribute. How can I get it to return the classes formatted?

For instance, in this case, I want the variable classes to have a value of .example.whatever instead of example whatever.

I've searched and the only solution that seemed to be provided is the code I demonstrated above.

Share Improve this question asked Apr 29, 2012 at 3:55 UserIsCorruptUserIsCorrupt 5,03515 gold badges40 silver badges42 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

I'm really very uneasy about this, since replacing spaces with periods will give the representation of stacked classes, when the classes aren't really stacked, but here you go:

// class="foo bar fiz buz" -> .foo.bar.fiz.buz
this.className.replace( /^|\s/g , "." );

Demo: http://jsbin./awitef/edit#javascript,html

$('button').click(function(){
  var classes = $(this).attr('class');
  alert("." + classes.split(" ").join(".") );
});

Fiddle here: http://jsfiddle/wxDEh/3/

本文标签: javascriptGet current element39s classes in jQueryStack Overflow