开发者

jquery dynamically genearate element id in a loop

开发者 https://www.devze.com 2023-01-02 16:47 出处:网络
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(

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>开发者_Python百科;");
$("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.


    <script type="text/javascript">
        $(function () {

            function createListItems(howmany, container) {
                for (i = 0; i < howmany; i++) {
                    container.append('<li id="listItem' + i + '">');
                }
            }

            createListItems(3, $('#unorderedList1'));

        });

    </script>
</head>
<body>
    <ul id="unorderedList1">

    </ul>
    </body>


You can simply do:

for (i=0;i<array.length;i++)
{
  //create HTML element of tag li
  $('#suggest').append("<li id='li" + i + "'></li>");
  $('#li'+i).html(array[i]);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消