Reputation: 4377
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:
Instead point #3 is not processed or at least the text is not displayed. Why?
Upvotes: 0
Views: 52
Reputation: 86882
Because a
is defined locally, it is a scope issue. Initialize a globally and it will work. See Below
$(document).ready(function($) {
var a = 0;
$("#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>');
a = 1;
}
});
});
Here is a fiddle
http://jsfiddle.net/jfhartsock/Khp7P/1/
Upvotes: 2
Reputation: 14219
It is a scope issue as mentioned above, the variable 'a' must be defined in the scope of the page, not the click event.
$(document).ready(function($) {
var a = 0;
$("#clickme").click(function() {
if (a == 1) {
$('#sometext').replaceWith('<div id="sometext">This is text TWO</div>');
a = 0;
}
else {
$('#sometext').replaceWith('<div id="sometext">This is text ONE</div>');
a = 1;
}
});
});
Upvotes: 2