Take the following example:
$.fn.foo = function() {
var $input = $('<input type="text"/>');
var $button_one = $('<button>One</button>');
var $button_two = $('<button>Two</button>');
$button_one.click(function(){
$input.val('hey');
});
$button_two.click(function(){
$input.replaceWith( $input.val('').clone( true ) );
});
this.append( $input, $button_one, $button_two );
};
Check the demo: http://jsbin.com/ezexah/1/edit
Now click “one” and you should see “hey” in the input. Next click “two” and then click “one” again and it doesn’t work. Even using the true option in clone to copy all events it still does not work. Any ideas?
You did not update
$input. It is still referring to the element you just removed, meaning$input.val('hey');will update the value of the DOM element that is now detached from the DOM tree..cloneor.replaceWithdo not automatically update existing references:This has nothing to do with the
trueoption btw, because you did not bind any event handlers to$input.DEMO