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

发布于 2024-10-01 18:24:48 字数 515 浏览 8 评论 0原文

我想知道 HTML5 附带的这些数据属性有哪些选择器。

以这段 HTML 为例:

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

是否有选择器可以获取:

  • "Companies" 下面所有带有 data-company="Microsoft" 的元素
  • 所有带有 data 的元素-company!="Microsoft" "Companies"
  • 在其他情况下,是否可以使用其他选择器,例如“包含、小于、大于等...”。

I would like to know what selectors are available for these data attributes that come with HTML5.

Taking this piece of HTML as an example:

<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...".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

暖心男生 2024-10-08 18:24:48
$("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"

查看jQuery选择器:contains是一个选择器,

这里是关于:包含选择器

$("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

here is info on the :contains selector

岁月苍老的讽刺 2024-10-08 18:24:48

jQuery UI 有一个 :data() 选择器< /a> 也可以使用。它似乎从 版本 1.7.0 就已经存在了。

您可以这样使用它:

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

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

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

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

获取 data-company 不等于 Microsoft

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

等的所有元素...< /em>

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

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

这对于您可能以这种或类似方式使用 $(...).data("datakey", "value") 的单页应用程序来说很好。

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

You can use it like this:

Get all elements with a data-company attribute

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

Get all elements where data-company equals 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

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. This means that for the above to work, defining the data in HTML is not enough. 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.

浪漫之都 2024-10-08 18:24:48

jsFiddle 演示

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

上面已经介绍了基本查询,并使用 John Hartsockanswer 将是获取每个数据公司元素的最佳选择,或者获取除 Microsoft 之外的所有元素(或任何其他版本的 :not< /代码>)。

为了将其扩展到您正在寻找的其他点,我们可以使用多个元选择器。首先,如果您要执行多个查询,最好缓存父选择。

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

接下来,我们可以在这个集合中查找以 G 开头的公司

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

,或者可能包含单词 soft 的公司。

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

也可以获取数据属性结尾匹配的元素

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>

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.

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

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

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>

俯瞰星空 2024-10-08 18:24:48

纯/普通 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'])"); 

querySelectorAll 您必须使用有效的 CSS 选择器(当前 Level3)

SPEED TEST (2018.06.29) 针对 jQuery 和 Pure JS:测试在 MacOs High Sierra 10.13.3 on Chrome 67.0.3396.99 (64位)、Safari 11.0.3(13604.5.6)、Firefox 59.0.2(64 位)。下面的屏幕截图显示了最快浏览器 (Safari) 的结果:

在此处输入图像描述

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

所以获胜者是 PureJS,最快的浏览器是 Safari(比 Chrome 快 8 倍以上!)

在这里,您可以在您的计算机上执行测试:https://jsperf.com/js-selectors-x

Pure/vanilla JS solution (working example here)

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

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

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 (!).

So winner is PureJS and fastest browser is Safari (more than 8x faster than Chrome!)

Here you can perform test on your machine: https://jsperf.com/js-selectors-x

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文