Knocking on trees was common in medieval times. It was thought that the wood sprites would counter bad luck if their tree was knocked on. Through the years, it came to be any wood, including wooden objects as well as trees, hence the idiom, "Knock on wood."
The idiom knock on wood is used to starve off bad luck mostly after making similar statements. It can also be referred to as touch wood and was mostly used by people who rap their knuckles on a piece of wood. The phrases are sometimes spoken when a person is already experiencing some good fortune and hope that it will continue.
Knocking on Wood used to be used by, I guess, supersticious people to ward off evil spirits/ fairies. It is often used when something bad happens, or when you want something good to continue. It is kind of like a gaurenteed reverse-jinx.
It comes from the old tradition. Trees would give oyu fruit as long as the spirit that inhabited that tree liked you and was favorable to you. You would knock on the wood of the tree to alert the spirit to your presence and thank them for the fruit you were taking and to ask for such favor in the future.
Later the Christian religion did as they always did. What they couldn't destroy they corrupted and the meaning was changed to say that knocking on wood was knocking NOT on a Tree Spirit's home, but knocking on Jesus's cross to ask favor and protection from God.
In certain European countries in the olden days, a criminal being chased by the authorities could seek refuge in a church. If the door were locked, he'd then have to knock on it until the vicar or parson or whoever opened for him, before the authorities got to him. In certain countries, the criminal would only have to so much as touch the door to be safe. The idea was that the parson or whoever could reform him and he didn't need to go to jail. Hence the terms "touch wood" and "knock on wood" being associated with luck.