【问题标题】:Regex in jQuery selector doesn't accept \d?jQuery 选择器中的正则表达式不接受 \d?
【发布时间】:2015-01-10 18:05:01
【问题描述】:

我试图只选择具有“example.com/foo/12345/bar”模式的链接,它们可以是任意位数。但是 jquery 似乎不接受 \d 的数字。还有其他建议吗?

$('a[href*="example.com\/foo\/\d+\/bar"]').hover(function(){});

【问题讨论】:

  • jQuery 在那里不接受正则表达式,但您可以在回调中使用filter,然后使用regex.test(this.href)
  • 属性选择器不接受正则表达式。您要么必须获取 ID 并迭代地执行匹配,要么使用自定义伪类:stackoverflow.com/questions/190253/…
  • 您可以尝试组合多个属性选择器,$('a[href*="example.com/foo"][href$="bar"]')

标签: javascript jquery regex jquery-selectors


【解决方案1】:

jQuery 在那里不接受正则表达式,但你可以使用filter:

$('a').filter(function() {
  return /example.com\/foo\/\d+\/bar/.test(this.href)
}).hover(function() {

})

【讨论】:

    猜你喜欢
    • 2010-09-16
    • 1970-01-01
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-14
    • 2023-03-24
    相关资源
    最近更新 更多