简体   繁体   English

使用HTML5的自定义数据属性的jQuery选择器

[英]jQuery selectors on custom data attributes using HTML5

I would like to know what selectors are available for these data attributes that come with HTML5. 我想知道哪些选择器可用于HTML5附带的这些数据属性。

Taking this piece of HTML as an example: 以这段HTML为例:

<ul data-group="Companies">
  <li data-company="Microsoft"></li>
  <li data-company="Google"></li>
  <li data-company ="Facebook"></li>
</ul>

Are there selectors to get: 是否有选择器:

  • All elements with data-company="Microsoft" below "Companies" 所有带有data-company="Microsoft"元素都在"Companies"之下
  • All elements with data-company!="Microsoft" below "Companies" 所有带有data-company!="Microsoft"元素都在"Companies"之下
  • In other cases is it possible to use other selectors like "contains, less than, greater than, etc...". 在其他情况下,可以使用其他选择器,如“包含,小于,大于等......”。
$("ul[data-group='Companies'] li[data-company='Microsoft']") //Get all elements with data-company="Microsoft" below "Companies"

$("ul[data-group='Companies'] li:not([data-company='Microsoft'])") //get all elements with data-company!="Microsoft" below "Companies"

Look in to jQuery Selectors :contains is a selector 查看jQuery选择器 :contains是一个选择器

here is info on the :contains selector 这是关于:包含选择器的信息

jQuery UI has a :data() selector which can also be used. jQuery UI有一个:data()选择器 ,也可以使用。 It has been around since Version 1.7.0 it seems. 它似乎从版本1.7.0开始。

You can use it like this: 你可以像这样使用它:

Get all elements with a data-company attribute 获取具有data-company属性的所有元素

var companyElements = $("ul:data(group) li:data(company)");

Get all elements where data-company equals Microsoft 获取data-company等于Microsoft所有元素

var microsoft = $("ul:data(group) li:data(company)")
                    .filter(function () {
                        return $(this).data("company") == "Microsoft";
                    });

Get all elements where data-company does not equal Microsoft 获取data-company不等于Microsoft所有元素

var notMicrosoft = $("ul:data(group) li:data(company)")
                       .filter(function () {
                           return $(this).data("company") != "Microsoft";
                       });

etc... 等等...

One caveat of the new :data() selector is that you must set the data value by code for it to be selected. 新的一个警告:data()选择器是您必须通过代码设置data值才能选择它。 This means that for the above to work, defining the data in HTML is not enough. 这意味着为了使上述工作,在HTML中定义data是不够的。 You must first do this: 你必须先这样做:

$("li").first().data("company", "Microsoft");

This is fine for single page applications where you are likely to use $(...).data("datakey", "value") in this or similar ways. 这适用于单页应用程序,您可能以这种或类似的方式使用$(...).data("datakey", "value")

jsFiddle Demo

jQuery provides several selectors (full list) in order to make the queries you are looking for work. jQuery提供了几个选择器(完整列表) ,以便使您正在寻找的查询工作。 To address your question "In other cases is it possible to use other selectors like "contains, less than, greater than, etc..."." 解决你的问题“在其他情况下,可以使用其他选择器,如”包含,小于,大于等......“。 you can also use contains, starts with, and ends with to look at these html5 data attributes. 您还可以使用contains,starts with和ends来查看这些html5数据属性。 See the full list above in order to see all of your options. 请参阅上面的完整列表,以查看所有选项。

The basic querying has been covered above, and using John Hartsock 's answer is going to be the best bet to either get every data-company element, or to get every one except Microsoft (or any other version of :not ). 上面已经介绍了基本的查询,并且使用John Hartsock答案将是获得每个数据公司元素或获得除Microsoft之外的每一个(或任何其他版本的:not )的最佳选择。

In order to expand this to the other points you are looking for, we can use several meta selectors. 为了将其扩展到您正在寻找的其他点,我们可以使用多个元选择器。 First, if you are going to do multiple queries, it is nice to cache the parent selection. 首先,如果您要进行多个查询,那么缓存父选择会很好。

var group = $('ul[data-group="Companies"]');

Next, we can look for companies in this set who start with G 接下来,我们可以在这个集合中寻找以G开头的公司

var google = $('[data-company^="G"]',group);//google

Or perhaps companies which contain the word soft 或者也许包含soft这个词的公司

var microsoft = $('[data-company*="soft"]',group);//microsoft

It is also possible to get elements whose data attribute's ending matches 也可以获得数据属性结尾匹配的元素

var facebook = $('[data-company$="book"]',group);//facebook

 //stored selector var group = $('ul[data-group="Companies"]'); //data-company starts with G var google = $('[data-company^="G"]',group).css('color','green'); //data-company contains soft var microsoft = $('[data-company*="soft"]',group).css('color','blue'); //data-company ends with book var facebook = $('[data-company$="book"]',group).css('color','pink'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul data-group="Companies"> <li data-company="Microsoft">Microsoft</li> <li data-company="Google">Google</li> <li data-company ="Facebook">Facebook</li> </ul> 

Pure/vanilla JS solution (working example here ) Pure / vanilla JS解决方案这里的工作示例)

// All elements with data-company="Microsoft" below "Companies"
let a = document.querySelectorAll("[data-group='Companies'] [data-company='Microsoft']"); 

// All elements with data-company!="Microsoft" below "Companies"
let b = document.querySelectorAll("[data-group='Companies'] :not([data-company='Microsoft'])"); 

In querySelectorAll you must use valid CSS selector (currently Level3 ) querySelectorAll中,您必须使用有效的CSS选择器 (当前为Level3

SPEED TEST (2018.06.29) for jQuery and Pure JS: test was performed on MacOs High Sierra 10.13.3 on Chrome 67.0.3396.99 (64-bit), Safari 11.0.3 (13604.5.6), Firefox 59.0.2 (64-bit). jQuery和Pure JS的SPEED TEST (2018.06.29):测试是在Chrome 67.0.3396.99(64位),Safari 11.0.3(13604.5.6),Firefox 59.0.2(64)上的MacOs High Sierra 10.13.3上进行的位)。 Below screenshot shows results for fastest browser (Safari): 下面的屏幕截图显示了最快浏览器(Safari)的结果:

在此输入图像描述

PureJS was faster than jQuery about 12% on Chrome, 21% on Firefox and 25% on Safari. PureJS比jQuery快了大约12%在Chrome上,21%在Firefox上,25%在Safari上。 Interestingly speed for Chrome was 18.9M operation per second, Firefox 26M, Safari 160.9M (!). 有趣的是,Chrome的速度是每秒18.9M,Firefox 26M,Safari 160.9M(!)。

So winner is PureJS and fastest browser is Safari (more than 8x faster than Chrome!) 因此,赢家是PureJS ,最快的浏览器是Safari (比Chrome快8倍!)

Here you can perform test on your machine: https://jsperf.com/js-selectors-x 在这里,您可以在您的机器上执行测试: https//jsperf.com/js-selectors-x

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM