jQuery 或 CSS 选择器选择所有以某个字符串开头的 ID [英] jQuery or CSS selector to select all IDs that start with some string

查看:19
本文介绍了jQuery 或 CSS 选择器选择所有以某个字符串开头的 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I select all elements whose id starts with "player_"?

我有多个这样的元素:

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

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

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

推荐答案

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

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):

div[id^="player_"]

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

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.

这篇关于jQuery 或 CSS 选择器选择所有以某个字符串开头的 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆