Вопрос

I encountered an issue using jQuery's .delegate() method on IE8 when removing the elements to which my delegate handler was attached. Here's the scenario: I had a table with rows that each had a delete button. The rows were created dynamically, so the delete button was wired up using delegate to handle the click events. When it came time to remove the last row, the entire table was removed (table was only created once there was a value to create at least one row.) This worked fine just about everywhere with the one exception of IE8. Even then, it worked on some pages, but just not one (the exact same code was used on each page.) For this one particular page, deleting that last row would generate a js error in IE8 stating "Object required" - the offending line being in the jQuery code for delegate.

So the question is, what's the best practice with handlers when some of the DOM elements those handlers are using are removed? Should undelegate be called at some point, and if so, where?

Это было полезно?

Решение

Use jQuery's .remove() method:

"Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed."

Or the .empty() method to remove all children but keep the top level element.

Другие советы

Kinakuta, from what you say it may simply be question of setting up the delegation correctly and phrasing the removal appropriately, rather than the use or not of remove() per se. It's hard to see why only IE8 should misbehave but probably some IE8 issue in jQuery.

With jQuery 1.7+ .on() replaces .bind(), .live() and .delegate() and may offer a way ahead. I would be looking to do something like this:

$("#myContainer").on("click", "button.delete", function(event){
    $(this).closest("tr", "#myContainer").remove();
});

You can no doubt achieve similar with .delegate() if you are using jQuery <1.7 .

As far as I can tell, it shouldn't matter, at the point of row removal, that the table and/or its rows were generated with MVC or any other generation method.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top