Concatenation in jQuery
var os = $.client.os; // mac
var browser = $.client.browser; // firefox
var browserversion = $.client.browserversion; // 3
$('#root').addClass( os + br开发者_JAVA技巧owser + browserversion );
.. results in <div id="root" class="macfirefox3">
. How do I add spaces between them?
$('#root').addClass( os + " " + browser + " " + browserversion );
Another variation of the same:
$('#root').addClass([
$.client.os,
$.client.browser,
$.client.browserversion
].join(' '));
Considering jQuery's philosophy, the addClass method should really accept an array or multiple strings as arguments without you having to concatenate them.
So here's my 2 cent plugin called addClasses, basically a wrapper around what Marko did.
jQuery.fn.addClasses = function() {
var classes = [];
$.each(arguments, function(index, name) {
classes.push(name);
});
this.addClass(classes.join(' '));
};
Allows you to send any number of class names as string arguments.
$('div').addClasses('message', 'greeting', 'w00t');
You need to concatenate spaces too, Falcon gave you an example already
精彩评论