jQuery检测添加列表项的时间(jQuery Detecting when list item is added)
我想用一个按钮将li附加到ul。 然后,当添加每个新列表项时,显示列表项的数量。 我可以添加李但不知道从哪里去。
任何指针都非常感谢。
<!doctype html> <html> <head> <meta charset="utf-8"> <title>List counter</title> </head> <body> <ul class="myUL"> </ul> <button class="myBUTTON">Add List Item</button> <p>List count>#</p> <script src="js/jquery-1.12.1.min.js"></script> <script> $('button.myBUTTON').on('click', function(eval) { eval.preventDefault(); $('ul.myUL').append('<li>Item 1</li>'); }); </script> </body> </html>I would like to append li to a ul with a button. Then as each new list item is added the number of list items is displayed. I can add the li but don't know where to go from there.
Any pointers are greatly appreciated.
<!doctype html> <html> <head> <meta charset="utf-8"> <title>List counter</title> </head> <body> <ul class="myUL"> </ul> <button class="myBUTTON">Add List Item</button> <p>List count>#</p> <script src="js/jquery-1.12.1.min.js"></script> <script> $('button.myBUTTON').on('click', function(eval) { eval.preventDefault(); $('ul.myUL').append('<li>Item 1</li>'); }); </script> </body> </html>最满意答案
您可以使用length来获取li计数并在click侦听器中设置它。
$('.myBUTTON').on('click', function() { // get the length before and directly increment by one to set it to the elements var length = ++$('.myUL li').length; $('.myUL').append('<li>Item ' + length + '</li>'); $('p').text('List count ' + length ); });<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <ul class="myUL"></ul> <button class="myBUTTON">Add List Item</button> <p>List count 0</p>You can just use the length to get the li count and set it in the click listener.
$('.myBUTTON').on('click', function() { // get the length before and directly increment by one to set it to the elements var length = ++$('.myUL li').length; $('.myUL').append('<li>Item ' + length + '</li>'); $('p').text('List count ' + length ); });<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <ul class="myUL"></ul> <button class="myBUTTON">Add List Item</button> <p>List count 0</p>
更多推荐
发布评论