Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery generate unique IDs

Here's what I have:

<a href="<?=$arItem["LINK"]?>"><?=$arItem["TEXT"]?></a>

It's a PHP array, which contains some links. I need to add an extra hash parameter #nav-link to the end of each link.

Here's how I tried do it:

<a id="likeLink" href=""><?=$arItem["TEXT"]?></a>
<script>
    $(document).ready(function () {
        $("#likeLink").attr("href", <?=$arItem["LINK"]?> + "#nav-link");
    });
</script>

But this code doesn't work because jQuery will not know which links I am linking to. So I guess that I need to generate the unique ids, but don't know how to do it.

like image 540
Mia Avatar asked Oct 05 '14 14:10

Mia


People also ask

How do I get a unique ID?

The simplest way to generate identifiers is by a serial number. A steadily increasing number that is assigned to whatever you need to identify next. This is the approached used in most internal databases as well as some commonly encountered public identifiers.

How to generate random ids in JavaScript?

In JavaScript, you can generate a random number with the Math. random() function.

How do you generate a random ID in react?

Uuid v4 is a React library or package that creates a universally unique identifier (UUID). It is a 128-bit unique identifier generator. The bits that comprise a UUID v4 are generated randomly and with no inherent logic.


2 Answers

I didn't need a forever unique/random id, just something that was unique per page, and all of these solutions seemed overkill for me so I came up with this:

var uniqId = (function(){
    var i=0;
    return function() {
        return i++;
    }
})();
like image 182
Scott Jungwirth Avatar answered Sep 16 '22 16:09

Scott Jungwirth


For generating random ids you could use this one.

<script type="text/javascript">
function Generator() {};

Generator.prototype.rand =  Math.floor(Math.random() * 26) + Date.now();

Generator.prototype.getId = function() {
   return this.rand++;
};
var idGen =new Generator();
</script>
</html>
<body>
<!-- Place this in the body of the page content -->

   <button onclick="console.log(idGen.getId())">click</button>

</body>
like image 35
Beri Avatar answered Sep 18 '22 16:09

Beri