[英]Get a class name by knowing part of it's name when it's not the only class applied to an element
I'm looking for a way using jquery/javascript to get a class name when I only know part of it and there are more than one classes applied to that element. 我正在寻找一种使用jquery / javascript来获取类名的方法,当我仅知道其中的一部分并且对该元素应用了多个类时。
So if I'm looking for a class that I know starts with "charLimit_" I want to know that full class name even when it's not the only class applied to a given element. 因此,如果我正在寻找一个以“ charLimit_”开头的类,我想知道该完整的类名,即使它不是应用于给定元素的唯一类。 Example HTML would be.
HTML就是示例。
<input class="charLimit_30 lastNameValidation" type="text" />
What I have so far below will put both "charLimit_30" and "lastNameValidation" into an array, but how do I then say I only want "charLimit_30" and then only tell me the value found after the underscore (30). 到目前为止,我将把“ charLimit_30”和“ lastNameValidation”都放入一个数组,但是我该如何说我只想要“ charLimit_30”,然后只告诉我在下划线(30)之后找到的值。
var classMName = $('[class*=charLimit_]').attr("class").split(' ');
Thanks in advance for you help!!! 在此先感谢您的帮助!!!
如果只需要第一次出现,并且类中下划线后面的所有内容都是数字,则可以执行以下操作:
$('[class*=charLimit_]').attr("class").match(/(?:\s|^)charLimit_(\d+)/)[1];
This is kinda like what inkedmn said, but in a more jQuery-ish way: 这有点像inkedmn所说的,但是以一种类似于jQuery的方式:
var numbersAfterCharLimit = [];
$('[class*="charLimit_"]').each(function() {
var matches;
if (matches = this.className.match(/(?:\s+|^)charLimit_([0-9]+)(?:\s+|$)/)) {
numbersAfterCharLimit.push(parseInt(matches[1], 10));
}
});
This appears to work (at least on stackoverflow): 这似乎起作用(至少在stackoverflow上):
var test = $('[class*=owner]').attr('class').split(' ');
for(i in test){
if(test[i].indexOf('post-sign') !== false){
test = test[i].split('-');
// replace this with a return
console.log(test[1]);
break;
}
}
And one that will work with the code that he is trying to do it with: 一个将与他尝试使用的代码一起工作的代码:
var test = $('[class*=charLimit_]').attr('class').split(' ');
for(i in test){
if(test[i].indexOf('charLimit_') !== false){
test = test[i].split('_');
// replace this with a return if it is in a function
console.log(test[1]);
break;
}
}
var classes = $('input').attr('class');
var myNum = '';
for(var i=0;i<classes.length;i++){
if(classes[i].match(/^charLimit_.*$/){
myNum = classes[i].split('_')[1];
}
}
Something like that would work, unless of course there's some jQuery magic way of doing it that I'm simply unaware of :) 这样的事情会起作用,除非当然有某种我完全不知道的jQuery魔术方法:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.