jQuery - 具有以特定字符串开头的类的匹配元素

时间:2021-05-10 19:23:31

I have a few links that look like this:

我有一些看起来像这样的链接:

<a href="#" class="somelink rotate-90"> ... </a>

How can I bind a function to all elements that have a class that starts with "rotate-" ?

如何将函数绑定到具有以“rotate-”开头的类的所有元素?

1 个解决方案

#1


9  

You can use starts with selector like this:

您可以像这样使用带选择器的开头:

$('a[class^="rotate-"]')

Description: Selects elements that have the specified attribute with a value beginning exactly with a given string.

说明:选择具有指定属性的元素,其值始于给定字符串。

So your code should be:

所以你的代码应该是:

$('a[class^="rotate-"]').click(function(){
  // do stuff
});

Note: If you want to find out elements that contain certain text anywhere in their attributes, you should do this instead:

注意:如果要查找属性中任何位置包含特定文本的元素,则应执行以下操作:

$('a[class*="rotate-"]').click(function(){
  // do stuff
});

#1


9  

You can use starts with selector like this:

您可以像这样使用带选择器的开头:

$('a[class^="rotate-"]')

Description: Selects elements that have the specified attribute with a value beginning exactly with a given string.

说明:选择具有指定属性的元素,其值始于给定字符串。

So your code should be:

所以你的代码应该是:

$('a[class^="rotate-"]').click(function(){
  // do stuff
});

Note: If you want to find out elements that contain certain text anywhere in their attributes, you should do this instead:

注意:如果要查找属性中任何位置包含特定文本的元素,则应执行以下操作:

$('a[class*="rotate-"]').click(function(){
  // do stuff
});