0

ボタンをクリックしてliを既存のulに追加し、他のボタンをクリックして1つずつ削除するjqueryがあります。作成は機能していますが、削除は機能していません。追加と削除を使用して、li を追加および削除しました。

これが私のコードです:

$(document).ready(function(){
    var ListView = Backbone.View.extend({
        el: $('body'), // el attaches to existing element 
        events: {
            'click button#add': 'addItem',
            'click button#remove': 'removeItem'
        },
        initialize: function(){
            _.bindAll(this, 'render', 'addItem','removeItem'); 
            this.counter = 0; // total number of items added thus far
            this.render();
        },
        render: function(){
            $(this.el).append("<button id='add'>Add list item</button>");
            $(this.el).append("<button id='remove'>Remove list item</button>");
            $(this.el).append("<ul></ul>");
        }, 
        addItem: function(){
            this.counter++;
            $('ul', this.el).append("<li>hello world"+this.counter+"</li>");
        },
        removeItem: function(){
            alert(this.counter);
            $('li',this.el).remove("<li>hello world"+this.counter+"</li>");
        }
    });
    var listView = new ListView(); 
});
4

5 に答える 5

1

その場合は、削除をクリックして最後の要素を削除しようとしているようです。アイテムの削除をに変更できます

addItem: function(){
    this.counter++;
    $('ul', this.el).append("<li class='count-"+this.counter+"'>hello world"+this.counter+"</li>");
},
removeItem: function(){
    $('li.counter-'+this.counter+,this.el).remove()
}
于 2013-11-13T07:28:08.303 に答える
0

html全体をremoveメソッドに渡してアイテムを削除することはできません。セレクターを使用する必要があるため、ID、クラス、タイプなどのいずれかです。

removeItem: function(e){
  $('ul',this.el).remove('li:nth-child('+counter+')');
}

これにより、カウンターに応じて、ul から 1 li が削除されます。1 つの特別な li を削除したい場合は、セットアップを変更する必要があります。これは、クリック時にどの li を削除するかをボタンがどのように認識できるかによるものです。

たとえば、li 自体を削除ボタンにすることができます。

events: {
 'click li': 'removeLi'
}

そして削除機能として:

removeLi: function(e){
  $(e.target).remove();
}

それが役に立てば幸い。

于 2013-11-13T07:23:00.827 に答える
0

または、あなたのものに固執するcounter

    removeItem: function(){
        alert(this.counter);

        this.$('li').eq(this.counter-1).remove();
        this.counter--;
    }

jQuery.eq()

于 2013-11-13T10:30:59.770 に答える
0

あなたの削除機能はバグです。「nth-child(nth)」CSSセレクターを使用してアイテムを削除できます...

removeItem: function(){
  $('ul ' + 'li:nth-child('+this.counter+')',this.el).remove()            
  this.counter--;
}
于 2013-11-14T18:13:38.280 に答える