可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
what it does:
<p class="foo"></p> $('p').addClass('bar');
output:
<p class="foo bar"></p>
what i need:
<p class="bar foo"></p>
So is it possible to add a class to an element to the first position?
edit (context): theres a split function on the last class right now. if another class is added its appended to the second split array as well.
回答1:
function prependClass(sel, strClass) { var $el = jQuery(sel); /* prepend class */ var classes = $el.attr('class'); classes = strClass +' ' +classes; $el.attr('class', classes); }
回答2:
(function($) { jQuery.fn.extend({ prependClass: function(newClasses) { return this.each(function() { var currentClasses = $(this).prop("class"); $(this).removeClass(currentClasses).addClass(newClasses + " " + currentClasses); }); } }); })(jQuery);
回答3:
This should not be a dependency for you in any way at all because of the limited control you have over the className string, but you can do this:
$("p").removeClass('foo').addClass('bar foo');
回答4:
You can try this, live demo:
http://jsfiddle.net/oscarj24/eZe4b/
$('p').prop('class', 'bar foo');
Otherwise you will need to play around with addClass and removeClass to get bar foo result in that order.
By the other hand, I don't get at all your question but if you just want to add bar foo class to the first p element just do this:
$('p').eq(0).prop('class', 'bar foo');
回答5:
Here's another way to do it.
$('#foo').attr('class', 'new-class ' + $('#foo').attr('class'));