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 に答える