jquery 正则表达式选择器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5733881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:43:53  来源:igfitidea点击:

jquery regex selector

jqueryregexjquery-selectors

提问by Nico AD

I want to select some html elements with name starting with btn (btn1, btn2..)

我想选择一些名称以 btn (btn1, btn2..) 开头的 html 元素

what is the most efficiant way to do that

最有效的方法是什么

I try http://james.padolsey.com/javascript/regex-selector-for-jquery/but dont manage to make it work

我尝试http://james.padolsey.com/javascript/regex-selector-for-jquery/但没有设法让它工作

$(':regex(class,btn[0-9]').hover( function(){

// not selecting any "btn" class

}

回答by Eli

If you want to select all elements that have a classattribute that starts with the word btn:

如果要选择class具有以单词开头的属性的所有元素btn

$( '[class^=btn]' )

If you want to use the nameattribute instead, just swap out the attribute:

如果您想改用该name属性,只需换出该属性:

$( '[name^=btn]' )

Using the attribute value starts-with selector: http://api.jquery.com/attribute-starts-with-selector/

使用属性值开始选择器:http: //api.jquery.com/attribute-starts-with-selector/

回答by Code Maverick

What you are doing is selecting all elements with the class of btnX where X could be 0-9.

您正在做的是选择所有具有 btnX 类的元素,其中 X 可以是 0-9。

To do this with the name attribute starting with "btn" you need to use:

要使用以“btn”开头的 name 属性执行此操作,您需要使用:

$(':regex(name,^btn)').hover(function() { ... }, function() { ... });

-- EDIT to include working jsFiddle demo--

--编辑以包括工作 jsFiddle 演示--

Also, don't forget to put this on your page:

另外,不要忘记把它放在你的页面上:

jQuery.expr[':'].regex = function(elem, index, match) {
    var matchParams = match[3].split(','),
        validLabels = /^(data|css):/,
        attr = {
            method: matchParams[0].match(validLabels) ?
                        matchParams[0].split(':')[0] : 'attr',
            property: matchParams.shift().replace(validLabels,'')
        },
        regexFlags = 'ig',
        regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
    return regex.test(jQuery(elem)[attr.method](attr.property));
}

回答by Talljoe

I doubt regex is the most efficient way to do it, but did you add the regex selector to your code? :regexis not a built-in selector so you need to include the snippet at the top of your article in your script.

我怀疑 regex 是最有效的方法,但是您是否将 regex 选择器添加到您的代码中? :regex不是内置选择器,因此您需要在脚本中包含文章顶部的代码段。