jQuery 查找只有部分引用 ID 的控件

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

jQuery Finding a control with only a partial reference ID

jqueryjquery-selectors

提问by Mark

is it possible to search for the a control on a webform, where you just want to match "anything" for part of it ie:

是否可以在网络表单上搜索 a 控件,您只想在其中匹配“任何内容”的一部分,即:

I have various buttons on a page - which take the id format: ID#(id1)#(id2)#(date) - for example:

我在页面上有各种按钮 - 采用 id 格式:ID#(id1)#(id2)#(date) - 例如:

ID-8258-3103-2011-12-18
ID-8258-3104-2011-12-18
ID-8258-3105-2011-12-18

I want to pass the (id1) and (date) in a querystring, and then have jQuery search for the first control on the page, which matches the (id1) and (date) and any(id2) - so for example, I pass 8252 and 2011-12-18 - so how would I find the first control above, from jQuery?

我想在查询字符串中传递 (id1) 和 (date),然后让 jQuery 搜索页面上的第一个控件,它匹配 (id1) 和 (date) 以及任何(id2) - 例如,我通过 8252 和 2011-12-18 - 那么我如何从 jQuery 找到上面的第一个控件?

$("#ID-8252-????????-2011-12-18")

回答by biziclop

Instead of using the #idselector, you can combine multiple attribute selectors, which filters the id attribute (one for the beginning of the id, one for the end):

#id您可以不使用选择器,而是组合多个属性选择器,过滤 id 属性(一个用于 id 的开头,一个用于结尾):

$('[id^="ID-8258"][id$="2011-12-18"]').addClass('found');

To select only the first match, use the :firstselector (not the same as the :first-childselector!)

要仅选择第一个匹配项,请使用:first选择器(与:first-child选择器不同!)

$('[id^="ID-8258"][id$="2011-12-18"]:first').addClass('found');

See http://api.jquery.com/category/selectors/for reference.

请参阅http://api.jquery.com/category/selectors/以供参考。

Example:

例子:

http://jsfiddle.net/wbLZ8/3/

http://jsfiddle.net/wbLZ8/3/

It seems that these selectors can be used even with IE7, if you want to use them in plain CSS.

如果您想在纯 CSS 中使用这些选择器,似乎这些选择器甚至可以与 IE7 一起使用。

回答by Mike Fahy

You'll want to use a filter in your selector, as discussed in jQuery selector regular expressions. (Check nickf's response for an example).

您需要在选择器中使用过滤器,如jQuery 选择器正则表达式 中所述。(以 nickf 的回复为例)。

回答by Serj Sagan