My code to set a global variable using eval
is not working. It's as if the assignment is not called at all, but no script errors occur.
<script type="text/javascript">
$(function() {
setTimeout(function() {
eval('var x = 1;');
alert(x);
}, 0);
});
</script>
<div onclick="alert(x);">Click to see 'x'</div>
When the page loads, the alert shows what I expect; it confirms that x = 1. But after that, I click on the div and get a javascript error that x
is undefined. How do I make eval
add this variable properly?
Background: The code above is a minimally reproducing example from a project I'm working on where we must execute javascript code during AJAX responses. eval
works properly most of the time, but this is causing problems.