I have a basic jQuery function going on:
$("#selector").click(function(){
$("#target").append("Some text to be added...");
});
That works fine, except I want to append different text on each sequential click. For example:
- First click appends text “Message 1”
- Second click appends text “Message 2”
- Third click appends text “Message 3”
and so on and so forth…
Also, I would like to set a limit, to say, 4 which after 4 clicks, nothing else happens.
Any help would be appreciated.
This will actually “append” them. If you wanted to replace each message each time, you’d use
.text()instead of.append().DEMO (using
.text()): http://jsfiddle.net/thVK6/The
ivariable will be incremented with each click. Wheniis equal tomessages.length, it will be reset to0.So with each click,
iis used to grab a new message from the Array.To further explain the increment trick, the
%modulo operator returns the remainder when dividingibymessages.length.When
iis equal tomessages.length, the remainder is0, so we’re back to the start.First click:
Second click:
Third click:
Fourth click:
…and so
iis now0again, so it starts over.So the same increment trick, but spelled out as above would be…
http://jsfiddle.net/thVK6/4/