Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
13
rated 0 times [  17] [ 4]  / answers: 1 / hits: 26006  / 12 Years ago, wed, december 26, 2012, 12:00:00

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');
}

More From » jquery

 Answers
34

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)


[#81223] Monday, December 24, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaleyv

Total Points: 259
Total Questions: 99
Total Answers: 107

Location: Saint Helena
Member since Tue, Nov 3, 2020
4 Years ago
;