计数器减少了什么问题?

时间:2021-04-05 09:07:51

I'm removing item from the list and the counter decreases by the number of the elements before the one to be removed instead of just decreasing by one

我正在从列表中删除项目,并且计数器减少了要删除的元素之前的元素数量而不是仅减少一个

Why is that ?

这是为什么 ?

 $(document).ready(function () {
    var count = 0;
            $("#clckToInsert").click(function () {
                var value = $('#misInput').val();
                var deleter = "<a href = #> X </a>";
                var li = '<li id = "item">' + value + deleter + '</li>'; 
                count++;
                $("#counter").html(count);
                $("#list").append(li);

                $('a').click(function () {
                    count--;
                    $(this).parent().remove();
                    $("#counter").html(count);

2 个解决方案

#1


1  

Inside of your #clckToInsert click handler, you are binding an additional click handler to every a every time it is fired:

在#clckToInsert单击处理程序内部,每次触发时都会绑定一个额外的单击处理程序:

$("#clckToInsert").click(function () {
    /* ... */
    $('a').click(function () {

So every time your #clckToInsert handler fires, every a on your page has an additional handler attached. So every click on an a fire that many handlers, decreasing that number of times.

因此,每次#clckToInsert处理程序触发时,页面上的每个处理程序都会附加一个附加处理程序。因此,每次点击许多处理程序的火灾,减少了这么多次。

#2


0  

You are binding the count-- callback to any <a> element. This means that you have n handlers for any given link.

您将count--回调绑定到任何元素。这意味着您有任何给定链接的处理程序。

If you changed something the following it should be ok.

如果您更改了以下内容,则应该没问题。

var $li = $(li)
$('#list').append($li)

$li.find('a').click

#1


1  

Inside of your #clckToInsert click handler, you are binding an additional click handler to every a every time it is fired:

在#clckToInsert单击处理程序内部,每次触发时都会绑定一个额外的单击处理程序:

$("#clckToInsert").click(function () {
    /* ... */
    $('a').click(function () {

So every time your #clckToInsert handler fires, every a on your page has an additional handler attached. So every click on an a fire that many handlers, decreasing that number of times.

因此,每次#clckToInsert处理程序触发时,页面上的每个处理程序都会附加一个附加处理程序。因此,每次点击许多处理程序的火灾,减少了这么多次。

#2


0  

You are binding the count-- callback to any <a> element. This means that you have n handlers for any given link.

您将count--回调绑定到任何元素。这意味着您有任何给定链接的处理程序。

If you changed something the following it should be ok.

如果您更改了以下内容,则应该没问题。

var $li = $(li)
$('#list').append($li)

$li.find('a').click