jQuery 检测何时添加列表项
jQuery Detecting when list item is added
我想用按钮将 li 附加到 ul。然后在添加每个新列表项时显示列表项的数量。我可以添加 li 但不知道从那里去哪里。
非常感谢任何指点。
<!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>
我想用按钮将 li 附加到 ul。然后在添加每个新列表项时显示列表项的数量。我可以添加 li 但不知道从那里去哪里。
非常感谢任何指点。
<!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>