简体   繁体   English

jQuery 选择器正则表达式

[英]jQuery selector regular expressions

I am after documentation on using wildcard or regular expressions (not sure on the exact terminology) with a jQuery selector.我正在寻找有关使用 jQuery 选择器使用通配符或正则表达式(不确定确切的术语)的文档。

I have looked for this myself but have been unable to find information on the syntax and how to use it.我自己寻找过这个,但一直无法找到有关语法和如何使用它的信息。 Does anyone know where the documentation for the syntax is?有谁知道语法的文档在哪里?

EDIT: The attribute filters allow you to select based on patterns of an attribute value.编辑:属性过滤器允许您根据属性值的模式进行选择。

You can use the filter function to apply more complicated regex matching.您可以使用filter函数来应用更复杂的正则表达式匹配。

Here's an example which would just match the first three divs:这是一个仅匹配前三个 div 的示例:

 $('div') .filter(function() { return this.id.match(/abc+d/); }) .html("Matched!");
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="abcd">Not matched</div> <div id="abccd">Not matched</div> <div id="abcccd">Not matched</div> <div id="abd">Not matched</div>

James Padolsey created awonderful filter that allows regex to be used for selection. James Padolsey 创建了一个很棒的过滤器,允许使用正则表达式进行选择。

Say you have the following div :假设您有以下div

<div class="asdf">

Padolsey's :regex filter can select it like so: Padolsey 的:regex过滤器可以像这样选择它:

$("div:regex(class, .*sd.*)")

Also, check the official documentation on selectors .另外,请查看有关选择器官方文档

UPDATE: : syntax Deprecation JQuery 3.0更新: :语法弃用的JQuery 3.0

Since jQuery.expr[':'] used in Padolsey's implementation is already deprecated and will render a syntax error in the latest version of jQuery, here is his code adapted to jQuery 3+ syntax:由于在 Padolsey 的实现中使用的jQuery.expr[':']已经被弃用,并且会在最新版本的 jQuery 中呈现语法错误,这里是他的代码适用于 jQuery 3+ 语法:

jQuery.expr.pseudos.regex = jQuery.expr.createPseudo(function (expression) {
    return function (elem) {
        var matchParams = expression.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));
    }
});

These can be helpful.这些可能会有所帮助。

If you're finding by Contains then it'll be like this如果你是通过Contains找到的,那么它会是这样的

    $("input[id*='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you're finding by Starts With then it'll be like this如果你是通过Starts With找到的,那么它会是这样的

    $("input[id^='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you're finding by Ends With then it'll be like this如果你通过Ends With找到,那么它会是这样的

     $("input[id$='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you want to select elements which id is not a given string如果要选择id 不是给定字符串的元素

    $("input[id!='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you want to select elements which name contains a given word, delimited by spaces如果要选择名称包含给定单词的元素,以空格分隔

     $("input[name~='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you want to select elements which id is equal to a given string or starting with that string followed by a hyphen如果要选择id 等于给定字符串或以该字符串开头后跟连字符的元素

     $("input[id|='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If your use of regular expression is limited to test if an attribut start with a certain string, you can use the ^ JQuery selector.如果您使用正则表达式仅限于测试属性是否以某个字符串开头,则可以使用^ JQuery 选择器。

For example if your want to only select div with id starting with "abc", you can use:例如,如果您只想选择 id 以“abc”开头的 div,您可以使用:

$("div[id^='abc']")

A lot of very useful selectors to avoid use of regex can be find here: http://api.jquery.com/category/selectors/attribute-selectors/可以在这里找到许多非常有用的选择器来避免使用正则表达式: http : //api.jquery.com/category/selectors/attribute-selectors/

var test = $('#id').attr('value').match(/[^a-z0-9 ]+/);

给你!

Add a jQuery function,添加一个 jQuery 函数,

(function($){
    $.fn.regex = function(pattern, fn, fn_a){
        var fn = fn || $.fn.text;
        return this.filter(function() {
            return pattern.test(fn.apply($(this), fn_a));
        });
    };
})(jQuery);

Then,然后,

$('span').regex(/Sent/)

will select all span elements with text matches /Sent/.将选择文本匹配 /Sent/ 的所有跨度元素。

$('span').regex(/tooltip.year/, $.fn.attr, ['class'])

will select all span elements with their classes match /tooltip.year/.将选择所有类匹配 /tooltip.year/ 的跨度元素。

ids and classes are still attributes, so you can apply a regexp attribute filter to them if you select accordingly. ids 和 classes 仍然是属性,因此如果您进行相应的选择,您可以对它们应用正则表达式属性过滤器。 Read more here: http://rosshawkins.net/archive/2011/10/14/jquery-wildcard-selectors-some-simple-examples.aspx在此处阅读更多信息: http : //rosshawkins.net/archive/2011/10/14/jquery-wildcard-selectors-some-simple-examples.aspx

$("input[name='option[colour]'] :checked ")

I'm just giving my real time example:我只是给出我的实时示例:

In native javascript I used following snippet to find the elements with ids starts with "select2-qownerName_select-result".在本机 javascript 中,我使用以下代码段查找 id 以“select2-qownerName_select-result”开头的元素。

document.querySelectorAll("[id^='select2-qownerName_select-result']");

When we shifted from javascript to jQuery we've replaced above snippet with the following which involves less code changes without disturbing the logic.当我们从 javascript 转移到 jQuery 时,我们用以下代码替换了上面的代码片段,这在不干扰逻辑的情况下涉及较少的代码更改。

$("[id^='select2-qownerName_select-result']")

如果您只想选择包含给定字符串的元素,则可以使用以下选择器:

$(':contains("search string")')

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

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