Use jQuery to get a list of classes
I have a un-ordered (ul
) HTML list. Each li
item has 1 or more classes attached to it.
I want to go through this ul
list and get all the (distinct) classes. Then from this list create a list of checkboxes 开发者_如何学Pythonwhose value matches that of the class and also whose label matches that of the class. One checkbox for each class.
What is the best way to do this using jQuery?
Try this:
// get the unique list of classnames
classes = {};
$('#the_ul li').each(function() {
$($(this).attr('class').split(' ')).each(function() {
if (this !== '') {
classes[this] = this;
}
});
});
//build the classnames
checkboxes = '';
for (class_name in classes) {
checkboxes += '<label for="'+class_name+'">'+class_name+'</label><input id="'+class_name+'" type="checkbox" value="'+class_name+'" />';
};
//profit!
i also needed this functionality but as a plugin, thought i share it...
jQuery.fn.getClasses = function(){
var ca = this.attr('class');
var rval = [];
if(ca && ca.length && ca.split){
ca = jQuery.trim(ca); /* strip leading and trailing spaces */
ca = ca.replace(/\s+/g,' '); /* remove doube spaces */
rval = ca.split(' ');
}
return rval;
}
精彩评论