jQuery - 选择所有带有属性名称(非值)的元素,以...开头?

jQuery  - 选择所有带有属性名称(非值)的元素,以...开头?

问题描述:

说我正在寻找所有具有属性data-language的元素,其值以java开头(将匹配java和javascript)。我知道如何做到:

Say I'm looking for all elements with an attribute 'data-language', whose value begins with 'java' (would match both 'java' and 'javascript'). I know how to do this:

$('[data-language^="java"]')

但我的问题是:如何获取所有具有属性的元素( 的属性,但实际属性名称本身)?例如:

But my question is: how do I get all elements that have an attribute (not the value of the attribute, but the actual attribute name itself) beginning with something? For example:


  1. 属性名称以data-s开头的所有元素,或

  2. 所有具有数据属性的元素(属性以data - 开头)。


没有快捷方式,您可以使用属性集合:

There is no shortcut, you may use the attributes collection :

 $(someselector).filter(function(){
      var attrs = this.attributes;
      for (var i=0; i<attrs.length; i++) {
          if (attrs[i].name.indexOf("someStartOfName")==0) return true;
      }         
      return false;
 });