Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS or Jquery create unique span ID

I'm creating a li item with a span inside. I've built an onclick function in the span to grab the parent li's ID to pass into a JSON get request. I'm unsure of how to create a unique ID and read it in the JS function. Since this is built dynamically I didn't build a switch but I feel like i'm missing another option. The problem here is that I can't capture the Li ID. I've tried this and also tried based on class, but all seem to be failing.

Li object creation:

$("#jdLists").append('<li class="bigger" id = "' + item.ID + '">'+ 
  item.GROUP_NAME + 
  '<span title="Remove from list" class=" Sp icon icon-color icon-plus" style="float: right; vertical-align: middle;" '+
  'onclick="spAdd()"></span>' + 
  '</li>');

on click function:

function spAdd() {
  $(this).closest("li").attr('id');
}
like image 656
atlMapper Avatar asked Dec 26 '12 17:12

atlMapper


2 Answers

Try like this:

// Should work for most cases
function uniqId() {
  return Math.round(new Date().getTime() + (Math.random() * 100));
}

// Create elements properly and attach click event
// before appending to DOM so it delegates the event
var $li = $('<li/>', {
  'class': 'bigger',
  id: uniqId()
});

var $span = $('<span/>', {
  'class': 'Sp icon icon-color icon-plus',
  title: 'Remove from list',
  text: 'I\'m a span',
  click: function() { 
    alert( $(this).parent().attr('id') );
  }
});

$('#jsLists').append( $li.append( $span ) );

It should alert the li's random id on click. Also instead of inline css, add another class for those styles; better, simpler, easier.

Demo: http://jsbin.com/avevim/1/edit (ctrl+enter to refresh and get new id)

like image 124
elclanrs Avatar answered Nov 16 '22 03:11

elclanrs


Underscore provides a uniqueId function for cases like this. Rather than being tricky with dates and random numbers, it just keeps a global counter and increments it each time the function is called:

var idCounter = 0;
_.uniqueId = function(prefix) {
  var id = '' + ++idCounter;
  return prefix ? prefix + id : id;
};
like image 22
Ross Allen Avatar answered Nov 16 '22 04:11

Ross Allen