jQuery generating unique identifier from an element (or object)
I would like to know what would be the correct way to generate an unique identifier string from an object sa开发者_如何学Goy, a div for example. It should be
- Unique - well, something like pre 1.4 jQuery.data(element) but that uses cache, right?
- Stable - Remains the same as such after refresh and so, thus not based on Date/Time or cache.
- Generate from the contents of the element, For example, duplicating that element should basically give the same identifier.
- A string.
Regular basic ways to generate a default id, like increments, arrays is not sufficient here. Please share your wisdom.
Thanks in advance.
EDIT: Not for the element attribute ID please.
You could get the element contents (including the element itself) has a string, then implement something like String.hashCode() method as implemented in the java jdk.
The hash code for a String object is computed as
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)
Depending on your implementation/task/use of that, it may be preferable to implement this function on the server side though
So you basically need a js hashing function. Not exactly my field but I heard MurmurHash is fast enough (I guess usual suspects like MD5 or SHA1 would be to slow for js) and has js implementation.
精彩评论