开发者

How to get size of jQuery object

开发者 https://www.devze.com 2023-01-28 21:50 出处:网络
I\'m saving key-value pairs in div container by using: $( \'#div_id\').data( key, value); At the end I need to check if anything is stored in this div container.

I'm saving key-value pairs in div container by using:

$( '#div_id').data( key, value);

At the end I need to check if anything is stored in this div container.

So first I get the content by calling:

var data = $( '#div_id').data();

Then to check its size with data.length or data.size.

But both functions don't exists. As I know the data function in jquery returns an object, so I should be able to开发者_如何学编程 get the size of this object.

How do I get the size of the object returned by the data function in jquery?


Objects do not have a "size". You could count its properties, though:

function getPropertyCount(obj) {
    var count = 0,
        key;

    for (key in obj) {
        if (obj.hasOwnProperty(key)) {
            count++;
        }
    }

    return count;
}

Usage:

alert(getPropertyCount(data));


It's not the best idea to store those key/value pairs at this level on the object/node.

var data = $( '#div_id').data();

returns all data that is attached to this node, this would include event handlers for instance of there are any.

So the best solution is to create an object which contains all of your data:

$('#div_id').data('mydata', {});
/* ... */
$('#div_id').data('mydata')[key] = value;

To your actual question. Plain Javascript objects do not own a .length property. You have to check that for yourself, looping over the keys:

var mylen = 0;
for(var prop in $('#div_id').data('mydata')) {
    mylen++;  
}

This should be improved by also checking and calling the .hasOwnProperty() method which makes sure that the current property is not inheritated from somewhere in the prototype chain.


Do you know what "keys" you were using? if so, just check the keys, if not, store an Object or Array instead.

e.g.

var myStuff = {};
myStuff.date = new Date();
myStuff.name = "Santa Claus";
myStuff.lifeStory = "Once upon a time...";
$('#div_id').data('myData', myStuff);

Then when you need it back out, just grab that one key...

var data = $('#div_id').data('myData');

Keep in mind, that JavaScript Objects/"Maps" don't have a "length" or "size" method/property, so if you need to check if it contains something, a generic function like this should work.

function isObjEmpty(obj){
  for(var i in obj){
    return false;
  }
  return true;
}


Javascript Objects doesn't have an length property. But you could easily calculate it with a simple jQuery function.

$.fn.dataLength = function () {
    var i,
        n = 0,
        t = $(this);
    for (i in t.data()) {
        n += 1;
    }

    return n;
}

Then use it with $('#div_id').dataLength()

EDIT:

Mind the other answers about the data-structure in .data and the check for .hasOwnProperty

0

精彩评论

暂无评论...
验证码 换一张
取 消