This is a loop in a function intending to create elements <li>
and give each <li>
an unique id. But it's not working. I suspect it's a simple syntax error with the use of quote in .attr(). But I can't get a straight answer from Google.
for (i=0;i<array.length;i++)
{
//create HTML element of tag li
$('#suggest').append("<li></li>");
$("li").attr("id",'li'+i);
$('#li'+i).html(array[i]);
}
use it like this
$suggest = $('#suggest');
for (i=0;i<array.length;i++) {
$suggest.append($('<li/>', {
id: 'li'+i,
html: array[i]
}));
}
For best performance results do:
var str = '';
for (i=0;i<array.length; i++) {
str += '<li id=\'li' + i + '\'>' + array[i] + '</li>';
}
$('#suggest').append(str);
By writing $('li')
, you're setting the ID of every <li>
in the document.
You don't need to add IDs at all.
Instead, you should assemble each <li>
element before appending it, like this:
var newLi = $('<li></li>').html(array[i]);
//Do things to newLi
$('#suggest').append(newLi);
Note that if you add an event handler inside the loop, it will share the i
variable, leading to unexpected results.
Instead, if you need i
in the event handler, you should move the body of the loop to a separate function that takes i
as a parameter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With