Jokes happen when someone is missing the point.
Most of the time, a joke happen when the answer (payoff) to a question (setup) is unexpected or out of place. Bonus point if the joke answer is a correct answer. For example, if I show you my hand with three raised fingers and I ask you what you see, a joke answer could be anything between "pink sausages" and "a graysy man with a mustache". Still technically correct, it's not what the setup made us expect.
But the payoff of a joke can not come from thin air: it has to be related to what was happening in the scene to work better. If, for the same example as above, I had answered with "the miserable grass of autumn", we are entering non-sense zone and it's either hit or miss, depending on a lot of factors (from the overall tone of your story to the very personality of the character).
The more the joke blends in the context of the scene, the funnier it is. The perfect example for me are "What is it?" jokes from Airplane:
“Excuse me, sir, there’s been a little problem in the cockpit.”
“The cockpit? What is it?”
“It’s the little room at the front of the plane where the pilots sit. But that’s not important right now.”
There is your joke: unexpected (yet accurate), and mixes with the flow of the scene without interrupting it.
The setup of a joke is not necessarily a question
In my above examples, I used the question/answer format, which works well in dialogues between characters. But setup/payoff can work in context with literally anything, as long as someone is missing the important point.
Let's say one of your character has an important thing to say. The jester of the group will focus on how he is poorly dressed and all of his lines will be about what he perceived instead of what the other wants to say.
Or, one character needs help (for a simple task or even in danger of death), and the others keep talking as if nothing was happening or just don't seem to be troubled at all.
Another point to take into consideration is that, in my opinion, the best jokes do not mock a person, but the teller (for his misunderstanding of the question/situation). In the last example, if people were mocking the person in need of help, they are no longer jokers, they are salty a**holes, which gives a very different view on the character for the reader.
This is not exact science of course, because what make people laughs depends of a lot of variables. Or, if I had to rephrase this as a joke: "Flying a plane is no different than riding a bicycle. Just a lot harder to put baseball cards in the spokes" (still from Airplane).