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

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

jQuery selectors on custom data attributes using HTML5

javascriptjqueryjquery-selectorscustom-data-attribute

提问by Jose3d

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"
  • All elements with data-company!="Microsoft"below "Companies"
  • In other cases is it possible to use other selectors like "contains, less than, greater than, etc...".
  • 与所有元素data-company="Microsoft"下方"Companies"
  • 与所有元素data-company!="Microsoft"下方"Companies"
  • 在其他情况下,是否可以使用其他选择器,如“包含、小于、大于等......”。

回答by John Hartsock

$("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 Selectors:contains 是一个选择器

here is info on the :contains selector

这是关于:contains 选择器的信息

回答by rhughes

jQuery UIhas a :data()selectorwhich can also be used. It has been around since Version 1.7.0it seems.

jQuery UI有一个也可以使用的:data()选择器。它似乎自1.7.0 版以来一直存在。

You can use it like this:

你可以这样使用它:

Get all elements with a data-companyattribute

获取具有data-company属性的所有元素

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

Get all elements where data-companyequals Microsoft

获取data-company等于的所有元素Microsoft

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

Get all elements where data-companydoes 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 datavalue by codefor it to be selected. This means that for the above to work, defining the datain HTML is not enough. You must first do this:

:data()选择器的一个警告是您必须通过代码设置data值才能选择它。这意味着要使上述工作正常,在 HTML 中定义是不够的。你必须首先这样做:data

$("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")这种或类似方式使用的单页应用程序来说很好。

回答by Travis J

jsFiddle Demo

jsFiddle Demo

jQuery provides several selectors (full list)in order to make the queries you are looking for work. 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. See the full list above in order to see all of your options.

jQuery 提供了几个选择器(完整列表),以使您正在寻找的查询工作。解决您的问题“在其他情况下是否可以使用其他选择器,如“包含、小于、大于等......”。您还可以使用包含、开头和结尾来查看这些 html5 数据属性。查看上面的完整列表以查看您的所有选项。

The basic querying has been covered above, and using John Hartsock's answeris 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

或者可能包含“软”这个词的公司

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>

回答by Kamil Kie?czewski

Pure/vanilla JS solution(working example here)

纯/香草 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 querySelectorAllyou 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). Below screenshot shows results for fastest browser (Safari):

jQuery 和 Pure JS 的速度测试(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 上执行测试-少量)。下面的屏幕截图显示了最快浏览器 (Safari) 的结果:

enter image description here

在此处输入图片说明

PureJS was faster than jQuery about 12% on Chrome, 21% on Firefox and 25% on Safari. Interestingly speed for Chrome was 18.9M operation per second, Firefox 26M, Safari 160.9M (!).

PureJS 在 Chrome 上比 jQuery 快 12%,在 Firefox 上快 21%,在 Safari 上快 25%。有趣的是,Chrome 的速度为每秒 1890 万次操作,Firefox 26M,Safari 160.9M(!)。

So winner is PureJSand 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