jQuery:从多类元素获取类名称 [英] jQuery: Get class name from multiclass element

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

问题描述

我选择了以下元素.获得类名称icon_23123的最佳方法是什么?

I've selected the following element. What's the best way to get the class name icon_23123?

<div class="icon icon_23123"></div>

是否有类似[class ^ ="icon_"]的属性来选择属性而不是元素? 还是应该获取所有的类名,并循环查找以icon_开头的类?

Is there something like [class^="icon_"] to select attributes instead of elements? Or should I get all the class names, and loop through to find one that begins with icon_?

我想编写一个函数,该函数获取以icon_开头的任何类名,并且仅获取那些类名.最终,我想获得下划线之后的部分,但不一定是数字-我的计划是使用正则表达式(这些类名是常规的).

I want to write a function that gets any class name starting with icon_, and only those class names. Ultimately, I want to get the portion after the underscore, but it's not necessarily numeric- my plan was to use a regex (these class names are regular.)

我正在尝试从中获取类名称的元素已经被选中,我只需要从中获取类名称(不是文档中每个具有class ="icon _....."的元素)

The element I'm trying to get the class name from is already selected, I just need the class name from it (not every element in the document with a class="icon_.....")

EIDT3:我的真正问题是我将数据和样式混合在一起.由于我不在乎支持较旧的浏览器,因此我使用data-id来保存此数据的ID.

EIDT3: My real problem was that I mixed data and styling. Since I don't care to support older browsers, I'm using data-id to hold the id of this datum.

<div class="icon icon_23123" data-id="23123"></div>

推荐答案

如果使用类存储数据,HTML5提供了一种将数据附加到元素的更方便的方法—

If you use classes to store data, HTML5 provides a more convenient way to attach data to an element — data- attributes. For example:

<div class="icon" data-id="23123"></div>

然后,您可以直接读取属性(最跨浏览器的方式):

Then you can read the attribute directly (the most cross-browser way):

var id = myelement.getAttribute('data-id');

或使用本机 dataset 属性对象:

or use the native dataset property object:

var id = myelement.dataset.id;

或针对较旧的浏览器(IE10-)使用jQuery的 data() 方法:

or use the jQuery’s data() method for older browsers (IE10-):

var id = $(myelement).data('id');

也可以使用相同的data-属性通过诸如.icon[data-id="23123"]的属性选择器将各个样式附加到元素.

It is also possible to use the same data- attribute to attach individual styles to the element via an attribute selector like .icon[data-id="23123"].

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

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