Get the identifier of an element where it is not?

So, I am using jqPlot , which has this stupid requirement that the id attribute is needed for the chart.

However, my javascript uses jQuery, which works with elements, and I don't want to rely on a div with an id.

Can I somehow, given the jQuery $(this) element, generate an id on the fly for the div and pass that id to my jqPlot function?

Something like that:

 (function($){ //jquery plugin style $.fn.myPlot = function(){ //Somehow get id for "this" var generatedId = somehowCreateID(this); jqPlot.plot( generatedId ); } })(jQuery); 

Any advice appreciated!

+4
source share
3 answers

Since identifiers must be guaranteed to be unqiue, but not necessarily random, it is much better to just use a monotonically increasing identification number with an alpha prefix like this:

 function assignID(elem, prefix) { prefix = prefix || "autoId_"; if (elem.id) { return (elem.id); } else { if (!assignID.cntr) { assignID.cntr = 1; } var id = prefix + assignID.cntr++; elem.id = id; return(id); } } 

This uses the function property assignID.cntr to keep track of the counter, which increments it every time it is used, so the identifiers assigned here will never be the same as the previously assigned identifier.

Then you can make sure that any element always has an id by simply doing this:

 assignID(elem, "plot"); 

If you need a jQuery method that does this, you can do it this way:

 jQuery.assignIDCntr = 1; jQuery.fn.assignID = function(prefix) { prefix = prefix || "autoId_"; return this.each(function() { if (!this.id) { this.id = prefix + jQuery.assignIDCntr++; } }); } 

And then you will use it as follows:

 $(".myobjects").assignID("plot"); 
+4
source
 function generateID(element) { var id; do { id = "_" + Math.floor(Math.random() * 1000000000); } while (document.getElementById(id) != null); element.id = id; return id; } 
0
source

You can use a counter with a prefix of at least one letter (to match documents other than HTML5):

 (function($) { var counter = 0; $.fn.myPlot = function() { return this.each(function() { jqPlot.plot(this.id || (this.id = "plot" + counter++)); }); } })(jQuery); 
0
source

Source: https://habr.com/ru/post/1391329/


All Articles