jQuery 或 CSS 选择器来选择所有以某个字符串开头的 ID

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

jQuery or CSS selector to select all IDs that start with some string

jquerycssjquery-selectorscss-selectors

提问by matt

How can I select all elements whose idstarts with "player_"?

如何选择id以“player_”开头的所有元素?

I have multiple elements like this:

我有多个这样的元素:

<div id="player_290x3dfda">text</div>

Every idhas a unique stamp on it. How can I select all those elements, either with jQuery or with pure CSS?

每一个上面id都有独一无二的印记。如何使用 jQuery 或纯 CSS 选择所有这些元素?

回答by BoltClock

Normally you would select IDs using the ID selector #, but for more complex matches you can use the attribute-starts-with selector (as a jQuery selector, or as a CSS3 selector):

通常,您会使用 ID 选择器选择 ID #,但对于更复杂的匹配,您可以使用 attribute-starts-with 选择器(作为jQuery 选择器或 CSS3 选择器):

div[id^="player_"]

If you are able to modify that HTML, however, you should add a class to your player divs then target that class. You'll lose the additional specificity offered by ID selectors anyway, as attribute selectors share the same specificity as class selectors. Plus, just using a class makes things much simpler.

但是,如果您能够修改该 HTML,则应该向播放器添加一个类,div然后以该类为目标。无论如何,您将失去 ID 选择器提供的额外特性,因为属性选择器与类选择器具有相同的特性。另外,仅仅使用一个类会让事情变得更简单。

回答by Prakash

try this:

尝试这个:

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

回答by Timon

You can use meta characters like *(http://api.jquery.com/category/selectors/). So I think you just can use $('#player_*').

您可以使用元字符,例如*( http://api.jquery.com/category/selectors/)。所以我认为你可以使用$('#player_*').

In your case you could also try the "Attribute starts with" selector: http://api.jquery.com/attribute-starts-with-selector/: $('div[id^="player_"]')

在您的情况下,您还可以尝试“属性开头为”选择器: http: //api.jquery.com/attribute-starts-with-selector/$('div[id^="player_"]')

回答by Riddhi

$('div[id ^= "player_"]');

This worked for me..select all Div starts with "players_" keyword and display it.

这对我有用..选择所有以“players_”关键字开头的 Div 并显示它。