I believe that is what $.data(element) does, it returns a unique id.
However, it only returns an integer number. I would prefer to combine
it with a few characters as well, but I suppose that isn't strictly
necessary.

Byron's function above is a good example of how you could use it. But
if you do create a function to handle this, I wouldn't name the
function "id" (which is a property name). I would name it
"uniqueId" or something else. And you might allow a parameter for the
additional characters instead of hard-coding the literal "jQuery_".
For example, if you generate ids like "div1", "div2", "div3" and then
you generate some more ids like "span1", "span2, "span3", it gives you
a little more control if you need to select those elements later--e.g.
$('[id^=div]') versus $('[id^=span]').

Generally, though, unless you do this a lot, it's pretty simple to
either generate your own random number or use $.data() right in the
assignment statement, like this:

  MyDiv.attr("id", "div" + (1 + Math.floor(9999 * Math.random()));

or

  MyDiv.attr("id", "div" + $.data(MyDiv));

The only problem I have with $.data() is that it doesn't look
semantically like something that produces a unique id. In fact, it is
a jQuery internal that otherwise is used to store and retrieve expando
data.

Larry


On Dec 26, 5:56 am, MorningZ <[EMAIL PROTECTED]> wrote:
> Why not just keep a "global" variable, like:
>
> var _id = 0;
>
> and when you create the new item, use that counter to make like "New_"
> + _id, and then increment the counter

Reply via email to