Javascript jQuery Select # id 以单词为前缀,以计数器为后缀

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11173188/
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-24 04:45:59  来源:igfitidea点击:

jQuery Select # id with word as prefix and counter as suffix

javascriptjquery

提问by MR.ABC

Is there a way to select all id's with jQuery with a prefix "my" and a suffix "0-9". Something like these $("#my$1-4") or is it just possible with a loop ?

有没有办法用jQuery选择所有带有前缀“my”和后缀“0-9”的id。像这样的 $("#my$1-4") 或者它是否可以使用循环?

    <div id="my1"/>
    <div id="my2"/>
    <div id="my3"/>
    <div id="my4"/>
    <div id="my5"/>

回答by David says reinstate Monica

First thoughts, which seems to work well:

第一个想法,这似乎运作良好:

$('div[id^="my"]').filter(
    function(){
        return this.id.match(/\d+$/);
    });

JS Fiddle demo.

JS小提琴演示

The above selects all divelements whose idstarts with the value my, and then filters the returned elements to those whose idalsoends with numeric characters.

以上选择了所有以 value 开头的div元素,然后将返回的元素过滤为那些以数字字符结尾的元素。idmyid

References:

参考:

回答by James Allardice

The prefix part is easily achievable with an attribute starts-withselector:

前缀部分可以通过属性开始选择器轻松实现:

$("div[id^=my]");

But there is no selector that will allow you to specify a range of characters, so a loop will have to be involved. I would suggest filter:

但是没有选择器可以让您指定一个字符范围,因此必须涉及一个循环。我建议filter

$("div").filter(function () {
    return /^my\d$/.test(this.id);
});

回答by Kyle Macey

Assuming you don't have millions of elements that start with "my", you could do:

假设您没有数百万个以“my”开头的元素,您可以这样做:

$('[id^=my]').filter(function() { return this.id.matches(/\d/) && this.id.length == 3 })

This grabs all elements that have an id starting with "my", contain a number, and are only 3 characters long (so "my54" will not match but "my6" will)

这会抓取所有 id 以“my”开头的元素,包含一个数字,并且只有 3 个字符长(所以“my54”不会匹配,但“my6”会)