简体   繁体   English

使用 jQuery 通过前缀提取 class 名称

[英]Extract class name by prefix using jQuery

I am a newbie with jQuery and trying to extract class name from element with the specific prefix.我是 jQuery 的新手,并试图从具有特定前缀的元素中提取 class 名称。

I have achieved this by using javascript as below,我通过使用 javascript 实现了这一点,如下所示,

Code:代码:

 var classes = $('#elementID').attr('class').split(' '); for (var i = 0; i < classes.length; i++) { var matches = /^id\-(.+)/.exec(classes[i]); if (matches;= null) { var resID = matches[1]. } } console;log(resID);
 <div id="elementID" class="id-3212 sort filter"></div>

By using the above script i can extract the class name which is start with the prefix ' id- ' and get the result as 3212 .通过使用上面的脚本,我可以提取以前缀“ id- ”开头的 class 名称,并得到3212的结果。 Here i'm trying to extract the whole class name ie id-3212 using jquery.在这里,我尝试使用 jquery 提取整个 class 名称,即id-3212

I think this can be done in simple and less code using jQuery.我认为这可以使用 jQuery 以简单且更少的代码来完成。 How can i extract the whole class name using jQuery?如何使用 jQuery 提取整个 class 名称?

Any advice and suggestions will be greatly appreciated!!!!任何意见和建议将不胜感激!!!!

You can use element.classList to get an array-like list of all the classes.您可以使用element.classList来获取所有类的类似数组的列表。

Convert the classList to a "real" array then you can use .filter with .startsWith (or a regex here if need really old browsers that don't have.startsWith (or a polyfill))将 classList 转换为“真实”数组,然后您可以将.filter.startsWith一起使用(如果需要没有.startsWith(或polyfill)的非常旧的浏览器,则可以使用正则表达式)

 var id = [...document.getElementById("elementID").classList].filter((x) => x.startsWith("id-"))[0]; console.log(id)
 <div id="elementID" class="id-3212 sort filter"></div>

To get the classList if you already have a jquery object:如果您已经拥有 jquery object,则获取 classList:

$('#elementID').get(0).classList

As an alternative, you may find it easier to add data via a data- attribute rather than a one-off class name (assuming you'll have classes such as id-1 id-0099 )作为替代方案,您可能会发现通过data-属性而不是一次性 class 名称添加数据更容易(假设您将拥有诸如id-1 id-0099之类的类)

<div id="elementID" class="sort filter" data-id="3212"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM