jQuery检测添加列表项的时间(jQuery Detecting when list item is added)

编程入门 行业动态 更新时间:2024-10-08 20:39:32
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> 
  
 

更多推荐

本文发布于:2023-08-03 17:44:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1396184.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时间   列表   jQuery   Detecting   added

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!