How Can I Create Js Event Listeners That Survive A Document.write?
Solution 1:
That is not possible. document.write
unloads the current document, and creates a new one.
A demo to confirm: http://jsfiddle.net/Gk3cX/
window.test = document; //Cache documentdocument.write('<button onclick="alert(window.test===document)">CLick</button>');
// Clicking shows false! The document has changed!
Your only choice for overwriting the current document without unloading is innerHTML
:
document.body.innerHTML = "Overwritten document's content, kept events.";
Solution 2:
The work-around I've found is to simply re-attach the listeners after the document.write.
Update: Doh! That works in Chrome, but FF throws an error:
attempt to run compile-and-go script on a cleared scope
Maybe if I unattach the handler before document.writing....
Update 2: nope: http://jsfiddle.net/sprugman/KzNbX/1/
Solution 3:
How about replacing document.write
with your own function, that way it won't destroy the page.
Something like this:
document.write = function(str){
document.body.innerHTML = str;
};
Or if you don't want to erase the whole page:
document.write = function(str){
document.body.innerHTML += str;
};
Solution 4:
i haven't tried this with document.write, but maybe it helps: http://api.jquery.com/live/
Attach an event handler for all elements which match the current selector, now and in the future
Post a Comment for "How Can I Create Js Event Listeners That Survive A Document.write?"