0

I'm only going to post the code that's relevant. If you need my whole code, let me know.

Anyway, I have the following code:

 var deck = [];
 var c = 0;
$('#add').click(function(){
     var addToDeck = $('input[name=searchItem]').val();
     addToDeck = addToDeck.toLowerCase();
     deck.push(addToDeck);
   $('#save').append('<div id="cardList' + (c++) + '">' + database[deck[deck.length-1]].name + '</div>');
 });

Which dynamically adds divs with unique id's each time a certain button is pressed (ex: cardList1, cardList2, etc). Now, if the user clicks on some div with a particular id (say cardList2), I want to remove it from the list.

I tried something like this:

  $(document).on('click','#save', function(){
   $('#cardList' + 'c').remove();
  });

But it doesn't work. I think I'm in the right direction though.

Just to re-iterate, this is a card game deck building application... so I want to make it easier on a user by letting them remove a card that's already in their deck just by clicking on the div with the card id.

4

2 回答 2

3

In your second code example, c is not defined or does not have the value you expect. This should work though:

$('#save').on('click','[id^=cardList]', function(){
   $(this).remove();
});

It will listen to click events on all elements having an ID which starts with cardList and which are descendants of the element #save (instead of listening to clicks on #save). It makes simpler because this will just refer to the element that was clicked and you want to remove.

You could also give the elements an additional class and use it instead of the attribute-starts-with selector:

// for example
$('<div />', {
    id: 'cardList' + (c++), 
    'class': 'myclass', 
    text: database[deck[deck.length-1]].name
}).appendTo('#save');

// somewhere else

$('#save').on('click','.myclass', function(){
   $(this).remove();
});

You should also think about whether you need unique IDs at all.

于 2013-02-05T18:03:16.580 回答
1

Create the new div as a jQuery object:

$('#save').append('<div>', {'id':'cardList' + (c++)});

Then it will be accesible.

于 2013-02-05T18:03:18.517 回答