Why doesn’t it work?
<body>
<p id="element_id">
blah
</p>
</body>
var pcontent = document.getElementById('element_id').innerHTML;
function exit(){
document.getElementById('id2').innerHTML = pcontent;
}
var a = '<div id="id2"><input type="button" value="exit" onclick= "exit()"></div>' ;
document.getElementById('element_id').innerHTML= a;
The problem here is not your code but instead the way in which you are running the code on jsfiddle. Your fiddle has the
onLoadoption set which means all of the javascript code runs in theonLoadcallback. So theexitfunction is defined in the callback and not in the global scope. Hence the event handler can’t referenceexit.This can be fixed by simply removing the
onLoadoption and instead usingno wrap (body)Working Fiddle: http://jsfiddle.net/NjbVh/
Or alternately you can force
exitto be a global by attaching it to thewindow.