使用 jQuery 获取类列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2787291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:16:25  来源:igfitidea点击:

Use jQuery to get a list of classes

jqueryjquery-selectors

提问by John

I have a un-ordered (ul) HTML list. Each liitem has 1 or more classes attached to it. I want to go through this ullist and get all the (distinct) classes. Then from this list create a list of checkboxes whose value matches that of the class and also whose label matches that of the class. One checkbox for each class.

我有一个无序 ( ul) HTML 列表。每个li项目都有 1 个或多个附加到它的类。我想浏览这个ul列表并获得所有(不同的)类。然后从这个列表中创建一个复选框列表,其值与类的值相匹配,并且其标签与类的标签相匹配。每个类一个复选框。

What is the best way to do this using jQuery?

使用 jQuery 执行此操作的最佳方法是什么?

回答by MDCore

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!

回答by Florian Fida

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;
}