2

鉴于此 HTML:

<div id="foo">
    <input type=button class="foo abtn_1">
    <input type=button class="joe bbtn_2">
    <input type=button class="doe cbtn_2">
    <input type=button class="joe dbtn_1">
    <input type=button class="foo ebtn_2">
</div>

单击时,我想获得带有下划线和数字的类的第一部分。

所以从第一个输入我会得到: abtn

目前我使用:

$('#foo input').on('click', function () {
    var a = $(this).attr('class')
                   .replace('foo','')
                   .replace('joe','')
                   .replace('doe','')
                   .replace('_1','')
                   .replace('_2','')

console.log(a);

});

我想应该有一个更健壮和更快的性能方式可能使用正则表达式来做到这一点?

4

3 回答 3

4

您可以使用正则表达式直接查找正确类名的正确部分,而无需进行任何替换:

$('#foo input').on('click', function () {
    var match = this.className.match(/(^|\s)([^\s_]+)_\d(\s|$)/);
    if (match) {
        var item = match[2];
        // do what you want with item here
    }
});

在这里工作演示:http: //jsfiddle.net/jfriend00/EDrvJ/

这是解释的正则表达式:

(^|\s)    Match starting with either the start of the string ^ or whitespace \s
([^\s_]+) After that, match any number of characters that are not whitespace and not underscore and capture this match
_\d       After that, match an underscore and any digit
(\s|$)    After that, match whitespace or the end of the string

(^|\s)开头和结尾的确保(\s|$)我们得到一个完整的类名匹配,而不仅仅是部分匹配。正则表达式中的|符号是 OR,因此我们可以将 a^或 a\s与匹配(^|\s)

于 2012-04-06T04:20:03.937 回答
2

它不是 jquery 替换,它是通用的 javascript 字符串替换

使用正则表达式可能看起来像:

var a = $(this).attr('class').replace(/(foo|joe|doe|_1|_2)/g, '');

如果你需要一些通用的东西

我想得到带有下划线和数字的类的第一部分。

然后使用

var a = $(this).attr('class').match(/\b([^ _]+?)_\d/, '');
于 2012-04-06T03:41:07.980 回答
1

根据这个测试,我建议你使用 split() 函数,并请更正句子“我想得到带有下划线和数字的类的第一部分”。,你的功能没有做你强调的事情

假设您需要没有数字和下划线的类的第一部分:

 $('#foo input').on('click', function () {
    var a = $(this).attr('class').split('_');
    console.log(a[0]);
   });
于 2012-04-06T04:53:49.137 回答