2

The program has two javascript functions to generate a table (generateTable) and delete one selected row (deleteOneRow).

generateTable function generates a table based on server data. Each row is in the following format:

<tr><td><span class="desc">aaa</span><a href="#delete_choice" class="delete-choice">Delete</a></td> </tr>

Basically, each row is some text followed by a 'delete' link. When the script finish the table generation, it calls $(".delete-choice").click(deleteOneRow) to bind click to the event handler.

In the event handler function deleteOneRow, it first simply deletes all the rows in the table. Then call generateTable again to display the remaining data entries. Code structure is like follows:

function deleteOneRow() {
    var choiceIdx = ... //get index
    $(".delete-choice").unbind('click');
    CurrentChoices.splice(choiceIdx, 1); // remove the entry from the array
    $("#problem-choice-table  tr").each(function(){ // delete the DOM entries
        $(this).remove();
    })
    generateTable();    
}

If the table have two rows, after clicking the delete link in the 1st row, the first row was deleted. Then it generates a table with the 2nd row moving to the 1st. However, the deleteOneRow is called again, then the 2nd row is removed eventually.

I guess this is due to event is fired multiple times. I tried unbind, stopPropagation, etc. Nothing works.

1 Answers1

2

Using jquery's live to attach an event is perfect for situations like this where content is added / removed dynamically and you want to match against the same selector, have you looked into using that?

Karl Rosaen
  • 4,508
  • 2
  • 27
  • 30
  • 2
    `live` is deprecated for jQuery 1.7. They now recommend using `on` or `delegate.` Delegate is preferred method for jQuery 1.4.2+ (just learned this myself) – mrtsherman Nov 09 '11 at 04:09
  • thanks mrtsherman, didn't realize the difference. here's a good q&a about the topic I found illuminating http://stackoverflow.com/questions/4579117/jquery-live-vs-delegate – Karl Rosaen Nov 09 '11 at 10:22
  • Using delegate indeed solves the problem. It is also more efficient. Thanks, guys. – Yuliang Han Nov 10 '11 at 19:51