$('*').data('tag', "tagged");
$('li[tag=tagged]').length
retur开发者_开发百科ns zero...
$('*').data('tag', "tagged");
$('li').each(
function()
{
if( $(this).data('tag') === "tagged" )
{
//do something taggy ...like increment a count
}
}
);
Or, for something reuseable:
function getTaggedInJquery( jQueryObj )
{
var total = 0;
jQueryObj.each(
function()
{
if( $(this).data('tag') === "tagged" )
total++;
}
);
return total;
}
alert( getTaggedInJquery( $('li') ) );
AFAIK the data(..)
method doesn't really set/append/create anything on the element you use it on.
It uses an internal dictionary object to hold the values and matches them via a uniquely generated id.
The solution proposed by Kevin Peno works but can get very costly very quick if you don't choose your selectors wisely.
Check http://jqueryjs.googlecode.com/files/jquery-1.3.2.js around line 1271++-
The selector you're using matches attributes on the HTML element, not jQuery data
items.
AFAIK, jQuery has no built-in selector that matches data
items.
You can either write your own selector or set your own attributes on the elements themselves.
var taggedElements = $.grep($('li').get(), function(n, i){
return ($(n).data('tag') == 'tagged');
});
精彩评论