When you use $("#on").click(function(){/*...*/}
, there isn't any element with id on
.
Then, that event handler isn't attached.
Moreover, when you use $("#off").click(function(){/*...*/}
, you add the event handler to the element that, in that moment, has the id off
. It doesn't matter if the id changes, the element is still the same and still has the same event handler.
To get the functionality you want, you can use event delegation to an ancestor with a filtering selector:
$("#button")
.on('click', '#on', function(){
document.getElementById("on").innerHTML="OFF";
document.getElementById("on").id="off";
alert(document.getElementById("button").innerHTML)
})
.on('click', '#off', function(){
document.getElementById("off").innerHTML="ON";
document.getElementById("off").id="on";
alert(document.getElementById("button").innerHTML)
});
Note this can be several times slower.
But a better alternative would be using id="myButton" data-state="off"
, and
$('#myButton').on('click', function() {
var state = $(this).data('state');
$(this).data('state', state==='on' ? 'off' : 'on');
state = state.toUpperCase();
$(this).html(state);
alert(state);
});