jQuery 1.4.4:如何根据其数据属性值查找元素? [英] jQuery 1.4.4: How to find an element based on its data-attribute value?

查看:106
本文介绍了jQuery 1.4.4:如何根据其数据属性值查找元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这应该是一件非常琐碎的任务,但是使用Mac上的Firefox 3.6.12,以下操作将无效:

I imagine this should be a pretty trivial task but using Firefox for Mac, 3.6.12 the following does not work:

// assign data attributes
$('.gallery li').each(function(i) {
    $(this).data('slide',i+1);
});

// outputting an empty jQuery object
console.log($('.gallery li[data-slide]'));

// this does not work either outputting an empty jQuery object
console.log($("[data-slide]"));

使用Firebug,我可以看到所有数据幻灯片属性(包括它们的数值)都已正确地附加到li并注销:

using Firebug I can see that all the data-slide attributes including their numerical value are correctly attached to the lis and logging out:

$('.gallery li').each(function(index) {
  console.log($(this).data());
});

预期的输出:

Object { slide=1}
Object { slide=2}
Object { slide=3}
Object { slide=4}

那为什么第一个console.log不起作用?

So why does the first console.log not work?

推荐答案

data将项目添加到jQuery的内部数据保存器中,而不是添加到data-属性中.这些被读入到jQuery的data()结构中,但是使用jQuery插入的值不会反馈到DOM中.

data adds items to jQuery's internal data holder, not to the data- attributes. These are read into jQuery's data() structure, but values inserted using jQuery are not fed back into the DOM.

最简单的方法是使用.filter():

// To replicate $('.gallery li[data-slide]')
$('.gallery li').filter(function(){
    return (undefined !== $(this).data('slide'));
});


您也可以将其作为自定义选择器:


You could also do this as a custom selector:

$.expr[':'].hasData = function(obj, index, meta, stack) {
    return (undefined !== $(obj).data(meta[3]));
};

$('.gallery li:hasData(slide)'); // li elements under .gallery with "slide" data set
$(':hasData(slide)'); // any element with "slide" data set

这篇关于jQuery 1.4.4:如何根据其数据属性值查找元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆