It is a custom known across the Western world and is generally used to avoid tempting fate. But different countries have slightly different customs.
In Hungary (well, at least where Anikó lives!), you need to touch the bottom of the wood, so the underside of a table will do nicely. Here in the UK, I think, any old bit of wood will do and many people, myself included, will tap on their own heads if there is nothing else around.
In Italy they touch iron – tocco ferro – particularly if seeing something related to death. In Bulgaria, чукам на дърво is used as protection against evil – but tables aren’t allowed. As here, knocking on one’s head, however, seems to be okay, often followed by the tugging of an earlobe…
It’s not altogether clear where this custom comes from but seems to go back to times when the spirits dwelt all over the place, and often in the trees. It could be that the knocking was to chase them away, stop them hearing about, and then changing, good luck, or even that it was to ask a favour. Whatever the origins, it seems to have stuck. And really works! (touch wood…)