使用jQuery获取类列表 [英] Use jQuery to get a list of classes

查看:58
本文介绍了使用jQuery获取类列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个无序(ul)HTML列表.每个li项目都具有一个或多个附加的类. 我想浏览此ul列表并获取所有(不同的)类.然后从该列表中创建一个复选框列表,这些复选框的值与类的值匹配,并且其标签与类的值匹配.每个课程一个复选框.

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 whose value matches that of the class and also whose label matches that of the class. One checkbox for each class.

使用jQuery做到这一点的最佳方法是什么?

What is the best way to do this using jQuery?

推荐答案

尝试一下:

// 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!

这篇关于使用jQuery获取类列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆