jQuery-从div读取所有类 [英] Jquery - Read all Classes from a div

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

问题描述

我正在尝试通过以下方式从HTML元素读取所有类名称.但这不起作用:

I'm trying to read all class names from HTML element in the following way. But it doesn't work:

HTML

<div id="test" class="fff aaa ccc" >hello world</div>

JS

if ($('#test').attr('class') != '')
{
   // Read classes
    var all_classes = $('#test').attr('class');

    // Output
    $('body').append('Classnames: '+all_classes+' ');

}

示例 http://www.jsfiddle.net/AQgqU/8/

有人可以帮我吗?

推荐答案

您可以这样做:

var classes = $('#test').attr('class').split(' ');

alert(classes[0]); // first class
alert(classes[1]); // second class
alert(classes[2]); // third class

或者您可以使用循环:

for(var i = 0; i < classes.length; i++) {
  alert(classes[i]);
}

更新:

如@KennyTM所建议的那样,使用上述代码,类名周围可能有空格.您可以使用jQuery的$.trim函数删除任何空格.

As suggested by @KennyTM, with above code there was possibility of space coming around a class name. You can use the $.trim function of jQuery to remove any space.

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

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