I wrote this simple code to understand why if I click the “click me” text for the second time JQuery does not display the “second” text.
<div id="clickme">Click me</div>
<div id="sometext">This is text ZERO</div>
<script type="text/javascript">
$(document).ready(function($) {
$("#clickme").click(function(){
if (a == 1) {
$('#sometext').replaceWith('<div id="sometext">This is text TWO</div>');
}
else {
$('#sometext').replaceWith('<div id="sometext">This is text ONE</div>');
var a = 1;
}
});
});
</script>
I expected the following behaviour:
- Page is loaded and the text ‘This is text ZERO’ is displayed
- I click the link the first time and JQuery displays ‘This is text ONE’
- I click the link a second time and jQuery displays ‘This is text TWO’
Instead point #3 is not processed or at least the text is not displayed. Why?
It is a scope issue as mentioned above, the variable ‘a’ must be defined in the scope of the page, not the click event.
http://jsfiddle.net/d5xSH/