【问题标题】:jQuery Select # id with word as prefix and counter as suffixjQuery Select #id 以 word 为前缀,counter 作为后缀
【发布时间】:2012-06-25 18:07:47
【问题描述】:

有没有办法用 jQuery 选择所有带有前缀“my”和后缀“0-9”的 id。 像这些 $("#my$1-4") 之类的东西,还是只能通过循环来实现?

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

【问题讨论】:

标签: javascript jquery


【解决方案1】:

最初的想法,似乎效果很好:

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

JS Fiddle demo.

上面选择了idmy开头的所有div元素,然后将返回的元素过滤为id以数字字符结尾的元素。 p>

参考资料:

【讨论】:

【解决方案2】:

前缀部分很容易通过attribute starts-with 选择器实现:

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

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

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

【讨论】:

    【解决方案3】:

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

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

    这会抓取所有 id 以“my”开头、包含数字且长度仅为 3 个字符的元素(因此“my54”将不匹配,但“my6”将匹配)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-30
      • 2017-12-02
      • 2012-12-31
      • 2015-08-16
      • 2018-11-01
      • 2016-06-17
      • 1970-01-01
      相关资源
      最近更新 更多