2

I am using JQuery .Html() to swap around the divs on my page using this code:

    $('#item1').html($('#item8').html());
    $('#item8').html('<p>sdsdsd</p>');

I've found that this works great, however the JQuery methods stop working. So div #item1 will have a toggle for example, it will work fine until I use .html().

Is there any solution to rebind the JQuery to fix this?

Thanks!

Funky
  • 12,890
  • 35
  • 106
  • 161
  • Where exactly are the event handlers bound to? Why don't you use DOM manipulation? `$('#item1').empty().append($('#item8').children());`? Don't use `.html()` as long as you don't have to. – Felix Kling Sep 02 '11 at 14:17
  • @Felix Kling: I was just about to suggest that in an answer, although you'd probably want `contents()` rather than `children()`. – Andy E Sep 02 '11 at 14:18
  • http://jsfiddle.net/X63tG/ This seems to work fine.... Are you saying that you've bound to an element within your divs, or to the divs themselves? Element inside of divs: use `live`. Divs themselves? Should work fine. – Adam Terlson Sep 02 '11 at 14:19
  • 1
    @Andy: Ah yes... well, depends on the content(s) ;) – Felix Kling Sep 02 '11 at 14:20
  • 1
    @Felix Kling: of course :-) Just playing it safe! – Andy E Sep 02 '11 at 14:23

3 Answers3

4

use .live and it will work

一二三
  • 21,059
  • 11
  • 65
  • 74
genesis
  • 50,477
  • 20
  • 96
  • 125
4

Instead of getting the HTML of the elements and then having the browser reparse it into another element, you could just move nodes from one container to another:

var $item8 = $('#item8');
$('#item1').empty().append($item8.contents());
$item8.html('<p>sdsdsd</p>');

This will keep any current bindings on the already created elements, so there's no need to use live() or rebind those events.

live(), or rather, delegate() is still a decent alternative solution, however.

Andy E
  • 338,112
  • 86
  • 474
  • 445
1

Use .delegate Docs See Jquery live() vs delegate() as to why you should use delegate over live.

$('itemParent').delegate('#item8', 'click', function(){});
Community
  • 1
  • 1
Loktar
  • 34,764
  • 7
  • 90
  • 104